2013-03-23 84 views
0

這部分程序做什麼(在Nubela's guthub上找到)?Python函數說明

def product(*args, **kwds): 
    """ 
    for py2.6< support (they lack itertools lib) 
    - http://docs.python.org/2/library/itertools.html#itertools.permutations 
    """ 
    pools = map(tuple, args) * kwds.get('repeat', 1) 
    result = [[]] 
    for pool in pools: 
     result = [x+[y] for x in result for y in pool] 
    for prod in result: 
     yield tuple(prod) 

,後來在節目:

list(set((product(*[range(2) for _ in range(length)])))) 

回答

1

它實現itertools.product的向後兼容性。看到的文檔product

itertools.product(* iterables [,重複])

輸入iterables的笛卡兒積。

等同於生成器表達式中的嵌套for循環。例如,產品(A,B)返回的結果與((x,y))相同,對於y中的x,在 B中爲y)。

嵌套循環像一個里程錶一樣循環,最右邊的元素在每次迭代中前進。此模式創建一個詞典 排序,以便如果輸入的可迭代序列被排序,產品 元組將按排序順序發出。

要計算迭代本身的乘積,請使用可選的repeat關鍵字參數指定重複次數。例如,對於 示例,產品(A,重複= 4)意味着與產品(A,A,A,A)相同。

此功能相當於下面的代碼,但實際執行中不 內存建立中間結果:

def product(*args, **kwds): 
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy 
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 
    pools = map(tuple, args) * kwds.get('repeat', 1) 
    result = [[]] 
    for pool in pools: 
     result = [x+[y] for x in result for y in pool] 
    for prod in result: 
     yield tuple(prod) 

注意如何在文檔中的代碼相匹配,你發現了什麼。

我不明白他們爲什麼在doc把參考itertools.permutations ... 代碼:

list(set((product(*[range(2) for _ in range(length)])))) 

AFAIK它相當於:

list(product(*[range(2) for _ in range(length)])) 

簡單地計算產品lengthrange(2) iterables。

+0

是的,完全是爲了計算排列。畢竟這是一個非圖解求解器。 – petajamaja 2013-03-23 16:51:47