'How to perform a mutation operation on binary values in list in Python

Suppose I have a chromosome given below. I want to perform a mutation operation on it. I want to change two genes from 0 to 1 or 1 to zero. But I have to select these two genes at random. How can i perform it on chromosome:1?

Chromosome:1=['0001010010011001111100111101101110111001011011111010011011000110100010100011011100011000101100111011110000011101100000000010110001010100011100001001001110101111']


Solution 1:[1]

Use sample from the random package of the standard library with parameter k=2 to select unique random positions in the string, then make some slice.

chromo = '0001010010011001111100111101101110111001011011111010011011000110100010100011011100011000101100111011110000011101100000000010110001010100011100001001001110101111'

import random

chromo_indexed = list(enumerate(chromo))

# get random pair
ch1, ch2 = random.sample(chromo_indexed, k=2)
while ch1[1] == ch2[1]:
    ch1, ch2 = random.sample(chromo_indexed, k=2)

# replace
g1 = '1' if ch1[1] == '0' else '0'
g2 = '1' if ch2[1] == '0' else '0'
#
new_chromo = chromo[:ch1[0]] + g1 + chromo[ch1[0]+1:]
new_chromo = new_chromo[:ch2[0]] + g2 + new_chromo[ch2[0]+1:]


print(f'{ch1} -> {g1}')
# (46, '1') -> 0
print(f'{ch2} -> {g2}')
# (60, '0') -> 1
print(new_chromo)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1