I need all possible combinations of 0,1 of length k.
Suppose k=2 I want (0,0), (0,1), (1,0), (1,1)
I have tried different function in itertools
but I did not find what I want.
>>> list(itertools.combinations_with_replacement([0,1], 2))
[(0, 0), (0, 1), (1, 1)]
>>> list(itertools.product([0,1], [0,1])) #does not work if k>2
[(0, 0), (0, 1), (1, 0), (1, 1)]
itertools.product()
takes a repeat
keyword argument; set it to k
:
product(range(2), repeat=k)
Demo:
>>> from itertools import product
>>> for k in range(2, 5):
... print list(product(range(2), repeat=k))
...
[(0, 0), (0, 1), (1, 0), (1, 1)]
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With