Created
January 28, 2009 20:26
-
-
Save vilterp/54167 to your computer and use it in GitHub Desktop.
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
import random | |
alphabet = 'abcdefghijklmnopqrstuvwxyz ' | |
def random_letter(): | |
return alphabet[random.randint(0,len(alphabet)-1)] | |
def random_string(length): | |
return ''.join([random_letter() for i in range(length)]) | |
def brute_force(goal): | |
while 1: | |
a = random_string(len(goal)) | |
if a == goal: | |
print 'Done!' | |
break | |
else: | |
print a | |
if __name__ == '__main__': | |
brute_force('to be or not to be') |
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
# idea from first paragraph: http://www.sciam.com/article.cfm?id=15-answers-to-creationist&page=4 | |
import random | |
characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234569890,.-()[]'?\"/!:=\\ " | |
def random_letter(): | |
return characters[random.randint(0,len(characters)-1)] | |
def random_string(length): | |
return ''.join([random_letter() for i in range(length)]) | |
def judge_fitness(phrase, goal): | |
fitness = 0 | |
for i in range(len(goal)): | |
if phrase[i] == goal[i]: | |
fitness += 1 | |
return float(fitness)/float(len(goal)) | |
def evolve(start, goal): | |
current_species = start | |
current_fitness = judge_fitness(start, goal) | |
while current_fitness < 1: | |
while True: | |
mutated = mutate(current_species) | |
mutated_fitness = judge_fitness(mutated, goal) | |
if mutated_fitness > current_fitness: | |
print '*** %s (%f)' % (mutated, mutated_fitness) | |
break | |
current_species = mutated | |
current_fitness = judge_fitness(current_species, goal) | |
print 'Done!' | |
def mutate(string): | |
a = [c for c in string] | |
a[random.randint(0,len(a)-1)] = random_letter() | |
return ''.join(a) | |
def go(goal): | |
start = random_string(len(goal)) | |
print 'starting with "%s"' % start | |
try: | |
evolve(start, goal) | |
except KeyboardInterrupt: | |
if __name__ == '__main__': | |
try: | |
while 1: | |
go(raw_input('Goal: ')) | |
except KeyboardInterrupt: | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment