Created
          July 12, 2013 18:09 
        
      - 
      
 - 
        
Save ctroller/5986516 to your computer and use it in GitHub Desktop.  
  
    
      This file contains hidden or 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 | |
| class DNA: | |
| def __init__(self): | |
| self.genes = [] | |
| self.fit = 0.0 | |
| for i in range(0,len(target)): | |
| self.genes.append(chr(random.randrange(32,128))) | |
| def fitness(self): | |
| ltarget = list(target) | |
| score = 0 | |
| for i in range(0,len(self.genes)): | |
| if(self.genes[i] == ltarget[i]): | |
| score = score + 1 | |
| if(score > 0): | |
| self.fit = score / len(ltarget) | |
| def crossover(self, partner): | |
| child = DNA() | |
| midpoint = int(random.randrange(len(self.genes))) | |
| for i in range(0, len(self.genes)): | |
| if(i > midpoint): | |
| child.genes[i] = self.genes[i] | |
| else: | |
| child.genes[i] = partner.genes[i] | |
| return child | |
| def mutate(self): | |
| for i in range(0, len(self.genes)): | |
| original = self.mutatedTarget() | |
| if(random.uniform(0, 1) < mutationRate): | |
| self.genes[i] = chr(random.randrange(32,128)) | |
| self.fitness() | |
| def mutatedTarget(self): | |
| return str.join("", self.genes) | |
| mutationRate = 0.02 | |
| totalPopulation = 1000 | |
| target = "Adolf Hitler" | |
| population = [] | |
| def setup(): | |
| for i in range(0,totalPopulation): | |
| population.append(DNA()) | |
| def draw(): | |
| matingPool = [] | |
| for pop in population: | |
| pop.fitness() | |
| n = int(pop.fit * 100) | |
| for j in range(0, n): | |
| matingPool.append(pop) | |
| for i in range(0, len(population)): | |
| a = random.randrange(len(matingPool)) | |
| b = random.randrange(len(matingPool)) | |
| while b == a: | |
| b = random.randrange(len(matingPool)) | |
| parentA = matingPool[a] | |
| parentB = matingPool[b] | |
| child = parentA.crossover(parentB) | |
| child.mutate() | |
| population[i] = child | |
| setup() | |
| best = population[0] | |
| i = 0 | |
| while(best.mutatedTarget() != target): | |
| draw() | |
| bestFit = 0.0 | |
| for p in population: | |
| if p.fit > bestFit: | |
| bestFit = p.fit | |
| best = p | |
| print("Generation " + str(i + 1) + ":") | |
| print(best.mutatedTarget()) | |
| i = i + 1 | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment