def findFit(target=42, length=20, pop=20, mutation=1):
    """Evolve a population of math problems to solve for target."""
    population = [makeChrom(length) for i in range(pop)]
    generations = 0
    while True:
        print "Generation: %s" %generations
        print "%s%s%s" %("Chromosome".rjust(15), "Result".rjust(15),
                                      "Fitness".rjust(15))
        done, population = sortFitness(population, target)
        if not done:
            # take the first several fittest members
            fittest = population[:pop/4]
            # and breed them until you have a new population
            population = breed(fittest, pop, mutation)
        else:
            print "Solution found!"
            print "%s = %s" %(decode(population[0]), eval(decode(population[0]))),
            print "is the fitest solution for %s!" %target
            return generations, decode(population[0])
        generations += 1
Evolve a population of math problems to solve for target.
recipes/Python/498257_Simple_functibase_Genetic/recipe-498257.py