I’m trying to write a program, where the input is a binary string with arbitrary length, as well as the number of bit flips desired, and the output is all the possible strings with the specified number of bit flips (in a list). For example, if the input is '110' and 2, the output is ['000','101','011']. I’m new to python and didn’t find any similar programs. I really have no idea how I can do that. Could anyone give me some hints? Many thanks for the help!!
>Solution :
Integer xor version of Ice Griffin’s answer.
from itertools import combinations
input_bits = '110'
flip_count = 2
# get all available single bit flips
flips = [1 << i for i in range(len(input_bits))]
combs = combinations(flips, flip_count)
# flip given bit string
def flip(bit_str, comb):
n = int(bit_str, 2) ^ sum(comb)
return f'{n:0{len(bit_str)}b}'
# implement combination
for comb in list(combs):
flipped = flip(input_bits, comb)
print(flipped)