2014-09-23 1 views
8

길이가 k 인 0,1의 모든 가능한 조합이 필요합니다.python 길이가 0 인 모든 가능한 조합

가정하자 K = 2 내가 itertools에 다른 기능을 시도했지만 내가 원하는 것을 찾지 못 하셨나요 (0,0), (0,1), (1,0), (1,1)

합니다.

>>> 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)] 
+0

을 나는 계산 빠른 :-) 의미 – Donbeo

답변

15

itertools.product()repeat 키워드 인수를; k로 설정 :

product(range(2), repeat=k) 

데모 : 빠른에 의해

>>> 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)]