Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I generate all possible binary strings with specified number of bit flips in python

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading