title: Python genetic algorithm for binary number
body: <p>I'm asked to make a genetic algorithm with the goal to determine an 8 bit string with the the most 1's and 0's. The eval function should return the number of changes plus 1. So for example 00000000 returns 1, 00011100 returns 3, and 01100101 returns 6. This is what I have:</p>
  
  <pre><code>def random_population():
      from random import choice
  
      pop = ''.join(choice(('0','1')) for _ in range(8))
      return pop   
  
  def mutate(dna):   
      """   For each gene in the DNA, there is a 1/mutation_chance chance 
      that it will be   switched out with a random character. This ensures 
      diversity in the   population, and ensures that is difficult to get stuck in 
      local minima.   """   
      dna_out = ""   
      mutation_chance = 100   
      for c in xrange(DNA_SIZE):
          if int(random.random()*mutation_chance) == 1:
              dna_out += random_char()
          else:
              dna_out += dna[c]   return dna_out
  
  def crossover(dna1, dna2):   
      """   Slices both dna1 and dna2 into two parts at a random index within their   
      length and merges them. Both keep their initial sublist up to the crossover   
      index, but their ends are swapped.   """   
      pos = int(random.random()*DNA_SIZE)
      return (dna1[:pos]+dna2[pos:], dna2[:pos]+dna1[pos:])
  
  def eval(dna):
      changes = 0
      for index, bit in enumerate(dna):
          if(index == 0):
              prev = bit
          else:
              if(bit != prev):
                  changes += 1
          prev = bit
      return changes+1
  
  
  #============== End Functions =======================#
  
  
  #============== Main ================# changes = 0
  
  prev = 0
  dna = random_population()
  print "dna: "
  print dna
  print eval(dna)
  </code></pre>
  
  <p>I am having trouble actually figuring out the genetic algorithm part (cross over / mutation). I should randomly pair the numbers and then randomly select a pair leaving one pair untouched and then cross over at a random point. Then it will end by randomly mutating one bit out of the entire population. The current code for crossover and mutate was just taken from a genetic algorithm example I found and was trying to understand. Any fhelp is welcome.</p>