A simplified genetic algorithm implemented by Python

Source: Internet
Author: User
In this article, we use the simplified genetic algorithm implemented by Python. the algorithm only uses mutation operators but does not use crossover operators, but the evolution is still very effective. the specific source code is as follows:

In this article, we use the simplified genetic algorithm implemented by Python. the algorithm only uses mutation operators instead of crossover operators, but the evolution is still very effective. the specific source code is as follows:

from string import ascii_lowercasefrom random import choice, randomtarget  = list("welcome to http://www.cnhup.com")charset = ascii_lowercase + ' .:/'parent  = [choice(charset) for _ in range(len(target))]minmutaterate  = .09C = range(100)perfectfitness = len(target)def fitness(trial):    return sum(t==h for t,h in zip(trial, target))def mutaterate(parent):    return 1.0-(1.0*(perfectfitness - fitness(parent)) / perfectfitness * (1.0 - minmutaterate))def mutate(parent, rate):    return [(ch if random() <= rate else choice(charset)) for ch in parent]def log(iterations,rate,parent):    print ("#%-4i, rate: %4.3f, fitness: %4.1f%%, '%s'" %           (iterations, rate, fitness(parent)*100./perfectfitness, ''.join(parent)))iterations = 0while parent != target:    rate =  mutaterate(parent)    iterations += 1    if iterations % 10 == 0: log(iterations,rate,parent)    copies = [ mutate(parent, rate) for _ in C ]  + [parent]    parent = max(copies, key=fitness)print ()log(iterations,rate,parent)


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.