2013-06-29 30 views
1

我想實現一個代碼,這個代碼在用戶設置大小的數組中循環,這意味着大小不是常量。在python中搜索動態數組內部

例如: A = [1,2,3,4,5] 那麼我所要的輸出是這樣的:

[1],[2],[3],[4],[5] 
[1,2],[1,3],[1,4],[1,5] 
[2,3],[2,4],[2,5] 
[3,4],[3,5] 
[4,5] 
[1,2,3],[1,2,4],[1,2,5] 
[1,3,4],[1,3,5] 
and so on 
[1,2,3,4],[1,2,3,5] 
[2,3,4,5] 
[1,2,3,4,5] 

你能幫我實現這個代碼?

回答

3

itertoolsdocumentation

def powerset(iterable): 
    "powerset([1,2,3]) -->() (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" 
    s = list(iterable) 
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) 

如果你不想空集,很容易清除。

(我假設在你的例子換行符沒有意義。如果他們這樣做,請解釋。)

1

您需要itertools.combinations

例子:

>>> from itertools import combinations 
>>> A = [1,2,3,4,5] 
>>> for i in xrange(1, len(A)+1): 
...  for c in combinations(A, i): 
...   print c 
...   
(1,) 
(2,) 
(3,) 
(4,) 
(5,) 
(1, 2) 
(1, 3) 
(1, 4) 
(1, 5) 
(2, 3) 
(2, 4) 
... 
... 
(2, 4, 5) 
(3, 4, 5) 
(1, 2, 3, 4) 
(1, 2, 3, 5) 
(1, 2, 4, 5) 
(1, 3, 4, 5) 
(2, 3, 4, 5) 
(1, 2, 3, 4, 5)