Skip to content

Instantly share code, notes, and snippets.

@Werkov
Created January 14, 2012 16:49
Show Gist options
  • Save Werkov/1612004 to your computer and use it in GitHub Desktop.
Save Werkov/1612004 to your computer and use it in GitHub Desktop.
Cumulative selection demo (inspired by Richard Dawkins)
#!/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