Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 10 and 01. 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. Below is 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

like image 756
J French Avatar asked Dec 17 '22 13:12

J French


1 Answers

You can use random.sample() function to get 5 unique indices from the list, and then flip them in a loop. Like that:

import random
genotype = [1,0,0,1,0,0,1,1,1,0]

random_five = random.sample(range(len(genotype)), 5)
for i in random_five:
    genotype[i] = 0 if genotype[i] == 1 else 1

print(genotype)

Output is:

[1, 1, 0, 1, 1, 0, 0, 1, 0, 1]
like image 146
ilyankou Avatar answered Dec 29 '22 16:12

ilyankou