Skip to content

Instantly share code, notes, and snippets.

@Lambdanaut
Created January 20, 2012 19:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Lambdanaut/1649116 to your computer and use it in GitHub Desktop.
Save Lambdanaut/1649116 to your computer and use it in GitHub Desktop.
A Genetic Algorithm that I wrote for Catherine K
#! /usr/bin/python
import random
#goal = "This message evolves like my love for you. I'll always love you, Cat. -Josh <3"
goal = "I Love You Cat"
generations = None
popSize = 25
mutation = 150 #Bigger = Less mutation
binaryOffset = 31
chromosomeLength = 7
goalLength = len(goal)
def randomAnimal():
chromosome = ""
for e in range(0,goalLength):
for i in range(0,chromosomeLength):
chromosome += str(random.randint(0,1))
return chromosome
population = [randomAnimal() for x in range(0,popSize)]
def padBin(binary):
newBin = binary
while len(newBin) < chromosomeLength:
newBin = "0" + newBin
return newBin
def charToBin(char):
return padBin(bin(ord(char)-binaryOffset)[2:])
def binToChar(binary):
return chr(int(binary,2)+binaryOffset)
def animalMeaning(chromosome):
meaning = ""
for char in range(0,goalLength):
position = char*chromosomeLength
meaning += binToChar(chromosome[position: position+chromosomeLength])
return meaning
def animalCode(meaning):
code = ""
for char in meaning:
code += charToBin(char)
return code
goalCode = animalCode(goal)
def fitness(chromosome):
score = 0
for char in range(0,goalLength*chromosomeLength):
if chromosome[char] == goalCode[char]: score += 1
return score
def breed(animal1,animal2):
newAnimal = ""
for x,y in zip(animal1,animal2):
# Mixing of DNA
toAdd = 0
if random.randint(0,1) == 0: toAdd = x
else: toAdd = y
# Mutate
if random.randint(0,mutation) == 0: toAdd = str(random.randint(0,1))
newAnimal += toAdd
return newAnimal
bestAnimalMeaning=""
# Only go through a specific number of generations
if generations:
for gen in (1,len(generations+1)):
pass
else:
# Work until the goal is found
while bestAnimalMeaning != goal:
bestScore = 0
bestAnimal = 0
count=0
for animal in population:
fit = fitness(animal)
if fit > bestScore:
bestScore = fit
bestAnimal = count
count+=1
newPopulation = []
bestAnimalCode = population[bestAnimal]
for animal in population:
newPopulation.append(breed(animal,bestAnimalCode))
population = newPopulation
bestAnimalMeaning = animalMeaning(population[bestAnimal])
print (bestAnimalMeaning)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment