Skip to content

Instantly share code, notes, and snippets.

@vilterp
Created January 28, 2009 20:26
Show Gist options
  • Save vilterp/54167 to your computer and use it in GitHub Desktop.
Save vilterp/54167 to your computer and use it in GitHub Desktop.
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')
# 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:
print
if __name__ == '__main__':
try:
while 1:
go(raw_input('Goal: '))
except KeyboardInterrupt:
print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment