Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 20th, 2012  |  syntax: None  |  size: 1.91 KB  |  hits: 4  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import random, string
  2. from operator import attrgetter
  3.  
  4. max_iters       = 1024
  5. start_pop       = 4096
  6. mutate_chance   = .25
  7. elite_chance    = .10 # keep the top
  8. elite      = int(start_pop*elite_chance)
  9. goal            = "Hello, World!"
  10. goal_len        = len(goal)
  11. options         = string.letters
  12. options += " !@#$%^&*()"
  13.  
  14. class Citizen:
  15.     def __init__(self, body):
  16.         self.fitness = citizen_fitness(body)
  17.         self.body = body
  18.  
  19.     def __repr__(self):
  20.         return self.body + " => " + str(self.fitness)
  21.  
  22. def mate(pop):
  23.     new_pop = pop[:elite]
  24.     for i in range(elite, start_pop):
  25.         rand1 = int((random.random() * 1000) % elite)
  26.         rand2 = int((random.random() * 1000) % elite)
  27.         rand_pos = int((random.random() * 100) % goal_len)
  28.         new_body = pop[rand1].body[:rand_pos] + pop[rand2].body[rand_pos:]
  29.  
  30.         if random.random() < mutate_chance:
  31.             new_body = mutate(new_body)
  32.  
  33.         new_pop.append(Citizen(new_body))
  34.     return new_pop
  35.  
  36. def mutate(body):
  37.     pos = int((random.random()*1000) % goal_len)
  38.     char = chr((ord(body[pos]) + int((random.random() * 200))) % 122)
  39.     return body[:pos] + char + body[pos+1:]
  40.    
  41.  
  42. def calc_fitness(str):
  43.     for p in pop:
  44.         p.fitness = citizen_fitness(p.body)
  45.     return pop
  46.  
  47. def citizen_fitness(str):
  48.     fitness = 0
  49.     for i in range(goal_len):
  50.         fitness += abs(ord(str[i]) - ord(goal[i]))
  51.     return fitness
  52.  
  53. def init_pop():
  54.     population = []
  55.  
  56.     for i in range(start_pop):
  57.         body = ""
  58.         for j in range(goal_len):
  59.             body += random.choice(options)
  60.         citizen = Citizen(body)
  61.         population.append(citizen)
  62.  
  63.     return population
  64.  
  65. if __name__ == '__main__':
  66.     pop = init_pop()
  67.     for i in range(max_iters):
  68.         pop = sorted(pop, key=attrgetter('fitness'))
  69.         print str(i) + ") " + str(pop[0]) # top performer
  70.  
  71.         if pop[0].fitness == 0:
  72.             break
  73.  
  74.         pop = mate(pop)
  75.         #print pop