Getting All possible bit combinations of bit-size N

David542 :

To test a full-adder I am combining all possible 0 or 1 inputs in three ways (one for input_a, one for input_b, and one for carry_c). To do this I am doing:

>>> [(bit1, bit2, bit3) for bit1 in a for bit2 in a for bit3 in a]
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

This works fine, but my two thoughts on this are:

  • Is there a more pythonic way to do this. Something like a built in combinations([0,1], 3)?
  • Would there be a way to abstract the list-comprehension so that for example I could do 20 possibilities without having to write it 20 times?

I've looked a bit at itertools but it seems like using that for the above case requires just about as much code (if not more) as the above list comprehension.

iz_ :

You can use product from itertools (Cartesian product):

from itertools import product

print(list(product([0, 1], repeat=3)))

Output:

[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

To change how many elements there are per tuple, you can alter the repeat argument.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360802&siteId=1
Bit
BIT