Skip to content

Instantly share code, notes, and snippets.

@maxcountryman
Created January 6, 2011 22:14
Show Gist options
  • Save maxcountryman/768705 to your computer and use it in GitHub Desktop.
Save maxcountryman/768705 to your computer and use it in GitHub Desktop.
Weasel program redux
import string, random
CHARS = string.uppercase + ' '
PROGENY = 100
RATE = 0.05
TARGET = 'METHINKS IT IS LIKE A WEASEL'
genotype = lambda s : [random.choice(s) for x in xrange(len(TARGET))]
phenotype = ''
def fitness(phenotype):
return sum([x == y for x,y in zip(phenotype, TARGET)])
def mutate(phenotype):
return [(random.choice(CHARS) if random.random() < RATE else c) for c in phenotype]
phenotypes = [''.join(genotype(CHARS)) for x in xrange(PROGENY)]
population = [''.join(mutate(l)) for l in phenotypes]
i = 0
while phenotype != TARGET:
points = []
for phenotype in population:
score = fitness(phenotype)
points.append(score)
winner = max(points)
phenotype = population[points.index(winner)]
population = [''.join(mutate(phenotype)) for x in xrange(PROGENY)]
print('{0}: {1} -- score: {2}'.format(i, phenotype, winner))
i += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment