lundi 25 mai 2020

How to randomly mutate 5 values in a binary list?

I'm writing a genetic algorithm in which i need to select 5 numbers from the binary list 'genotype' and flip them, so a 1=0 and 0=1.I tried putting my code in a loop with a range(1,6) however when I do this it still only changes one of the numbers. Bellow if my original code without the loop which randomly selects one of the binary values and mutates it. Does anyone know a better way of doing this but for 5 of the elements in the list?

genotype = [1,0,0,1,0,0,1,1,1,0]

def mutate(self):
  gene = random.choice(genotype)
  if genotype[gene] == 1:
    genotype[gene] = 0
  else:
    genotype[gene] = 1
  return genotype



Aucun commentaire:

Enregistrer un commentaire