Created
January 14, 2012 16:49
-
-
Save Werkov/1612004 to your computer and use it in GitHub Desktop.
Cumulative selection demo (inspired by Richard Dawkins)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
# WEASEL | |
# Inspired by Richard Dawkins. | |
# | |
from random import random, choice | |
genoverse = 'ABCDEFGHIJKLKMNOPQRSTUVWXYZ ' | |
target = list('METHINKS IT IS LIKE A WEASEL') | |
population = 100 | |
mutability = 0.05 | |
progeny = [choice(genoverse) for _ in target] | |
generation = 0 | |
while progeny != target: | |
individuals = [[choice(list(set(genoverse) - set(g))) if random() <= mutability else g for g in progeny] for _ in range(population)] | |
generation += 1 | |
progeny = max(individuals, key=lambda individual: sum([1 if x == y else 0 for x,y in zip(target, individual)])) | |
print("{}:\t{}".format(generation, ''.join(progeny))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment