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. 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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With