Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions hellogene.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import random, string

GA_POPSIZE = 2048
GA_ELITRATE= 0.10 # elitism rate
GA_MUTATIONRATE = 0.25 # mutation rate
GA_TARGET = "Hello world!"
GA_CHARS = string.ascii_lowercase + string.digits + string.punctuation + string.whitespace +string.ascii_uppercase

def randstr():
return "".join([random.choice(GA_CHARS) for i in range(len(GA_TARGET))])

def fitness(value):
return sum([abs(ord(value[j]) - ord(GA_TARGET[j])) for j in range(len(GA_TARGET))])

def mate(population, buffer):
esize = int(GA_POPSIZE * GA_ELITRATE)
for i in range(esize): # Elitism
buffer[i] = population[i]
for i in range(esize, GA_POPSIZE):
i1 = random.randint(0, GA_POPSIZE / 2)
i2 = random.randint(0, GA_POPSIZE / 2)
spos = random.randint(0, len(GA_TARGET))
buffer[i] = population[i1][:spos] + population[i2][spos:] # Mate
if random.random() < GA_MUTATIONRATE: # Mutate
pos = random.randint(0, len(GA_TARGET)-1)
buffer[i] = buffer[i][:pos] + random.choice(GA_CHARS) + buffer[i][pos+1:]

population = [randstr() for i in range(GA_POPSIZE)]
buffer = [randstr() for i in range(GA_POPSIZE)]
while True:
i+=1;
population = sorted(population, key=lambda c: fitness(c))
print (("round: %d variation: %d string generated: %s") % (i, fitness(population[0]), population[0]))
if not fitness(population[0]): # We're done, best match found
break
mate(population, buffer)
population, buffer = buffer, population