2010-02-19 27 views

回答

7

實施例是在itertools docs

>>> import itertools 
>>> for i in itertools.product(range(2), repeat=4): 
    print(i) 
+0

非常感謝大家的答案。結果我發現了一個格雷碼。弗蘭克格雷之後的格雷碼是一個二進制數字系統,其中兩個連續的值只有一位不同。 WikiPedia – 2010-02-19 16:27:33

0

參見product發生器。

該模塊實現了許多通過從APL,Haskell中,和SML構建啓發 迭代器積木。每個版本都已經重新編寫爲適合Python的 表單。

該模塊標準化了一組核心快速,高效的工具 ,這些工具可以單獨使用或組合使用。它們共同構成一個 「迭代代數」使其能夠簡潔而有效地構建專業 工具純Python

0
def print_all_combinations(max_value): 
    width = len('{0:0b}'.format(max_value)) 
    format_string = '{0:0%db}' % width 
    for i in xrange(max_value): 
     print format_string.format(i)
1
def f(n): 
    if n==1: 
     return ['0', '1'] 
    tmp = f(n-1) 
    return ['0'+v for v in tmp] + ['1'+v for v in tmp] 

>>> f(4) 
['0000', 
'0001', 
'0010', 
'0011', 
'0100', 
'0101', 
'0110', 
'0111', 
'1000', 
'1001', 
'1010', 
'1011', 
'1100', 
'1101', 
'1110', 
'1111'] 
1

您正在尋找K-組合。檢查this

你想看看功能是xcombinations:

def xcombinations(items, n): 
    if n==0: yield [] 
    else: 
     for i in xrange(len(items)): 
      for cc in xcombinations(items[:i]+items[i+1:],n-1): 
       yield [items[i]]+cc 
+0

感謝您的鏈接,關於我在別處需要的生成器和組合的大量信息。 – 2010-02-19 16:30:24

相關問題