Search code examples
pythonstringalgorithmbinarycombinations

Get all combinations of a binary string with bit flips at specific indices (Python)


I have a binary string. I have a list of bit indices to flip. How can I generate all possible combinations of binary strings with flips at those specific indices? The output list should contain 2^n unique elements where n is the length of the indices list. I believe itertools.product() could be used here, but I can't figure out how to line up all the parameters, especially since the length of the indices list is variable.

Example:

binaryString = "0000000000"
indicesToFlip = [0,1,9]

outputCombinations = magic()

print(outputCombinations)

["0000000000",
 "1000000000",
 "0100000000",
 "1100000000",
 "0000000001",
 "0100000001",
 "1000000001",
 "1100000001"]

Solution

  • Try:

    from itertools import combinations
    
    binaryString = "0000000000"
    indicesToFlip = [0, 1, 9]
    
    out = []
    for i in range(len(indicesToFlip) + 1):
        for c in combinations(indicesToFlip, i):
            out.append(
                "".join(
                    ("1" if ch == "0" else "0") if i in c else ch
                    for i, ch in enumerate(binaryString)
                )
            )
    
    print(*out, sep="\n")
    

    Prints:

    0000000000
    1000000000
    0100000000
    0000000001
    1100000000
    1000000001
    0100000001
    1100000001