Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python all possible combinations of 0,1 of length k

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)]
like image 473
Donbeo Avatar asked Sep 23 '14 09:09

Donbeo


1 Answers

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)]
like image 102
Martijn Pieters Avatar answered Oct 01 '22 10:10

Martijn Pieters