Search code examples
pythonlogical-operators

Combinaison of 1, 2, 3, 4 bits as 0 in 5bits


I'm trying to get all possible combination with 1 bit as 0, 2 bits as 0, ..., 4 bits as 0 in 5bits

for example for 1 bit it should be like that: [11110, 11101, 11011, 10111, 01111]

I'm using a list comprehension:

five_mask = int('11111', 2)
# for 1 bit
[five_mask ^ 2**i for i in range(0, 5)]
# for 2 bits
[five_mask ^ (2**i | 2**j) for i in range(0, 5) for j in range(i+1, 5)]
# for 3 bits
[five_mask ^ (2**i | 2**j | 2**k) for i in range(0, 5) for j in range(i+1, 5) for k in range(j+1, 5)]
...

It works but I thing there's a less repetitive and pretty way, any idea ?


Solution

  • One nice approach is to use the combinations function from itertools.

    from itertools import combinations
    
    d = {k:[sum(t) for t in combinations([2**i for i in range(5)],5-k)] for k in range(6)}
    

    The resulting dictionary:

    {0: [31],
     1: [15, 23, 27, 29, 30],
     2: [7, 11, 19, 13, 21, 25, 14, 22, 26, 28],
     3: [3, 5, 9, 17, 6, 10, 18, 12, 20, 24],
     4: [1, 2, 4, 8, 16],
     5: [0]}