Created
April 4, 2012 04:11
-
-
Save helloandre/2297649 to your computer and use it in GitHub Desktop.
Genetic Hello World
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, string | |
from operator import attrgetter | |
max_iters = 1024 | |
start_pop = 4096 | |
mutate_chance = .25 | |
elite_chance = .10 # keep the top | |
elite = int(start_pop*elite_chance) | |
goal = "Hello, World!" | |
goal_len = len(goal) | |
options = string.letters | |
options += " !@#$%^&*()" | |
class Citizen: | |
def __init__(self, body): | |
self.fitness = citizen_fitness(body) | |
self.body = body | |
def __repr__(self): | |
return self.body + " => " + str(self.fitness) | |
def mate(pop): | |
new_pop = pop[:elite] | |
for i in range(elite, start_pop): | |
rand1 = int((random.random() * 1000) % elite) | |
rand2 = int((random.random() * 1000) % elite) | |
rand_pos = int((random.random() * 100) % goal_len) | |
new_body = pop[rand1].body[:rand_pos] + pop[rand2].body[rand_pos:] | |
if random.random() < mutate_chance: | |
new_body = mutate(new_body) | |
new_pop.append(Citizen(new_body)) | |
return new_pop | |
def mutate(body): | |
pos = int((random.random()*1000) % goal_len) | |
char = chr((ord(body[pos]) + int((random.random() * 200))) % 122) | |
return body[:pos] + char + body[pos+1:] | |
def calc_fitness(str): | |
for p in pop: | |
p.fitness = citizen_fitness(p.body) | |
return pop | |
def citizen_fitness(str): | |
fitness = 0 | |
for i in range(goal_len): | |
fitness += abs(ord(str[i]) - ord(goal[i])) | |
return fitness | |
def init_pop(): | |
population = [] | |
for i in range(start_pop): | |
body = "" | |
for j in range(goal_len): | |
body += random.choice(options) | |
citizen = Citizen(body) | |
population.append(citizen) | |
return population | |
if __name__ == '__main__': | |
pop = init_pop() | |
for i in range(max_iters): | |
pop = sorted(pop, key=attrgetter('fitness')) | |
print str(i) + ") " + str(pop[0]) # top performer | |
if pop[0].fitness == 0: | |
break | |
pop = mate(pop) | |
#print pop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment