使用規範的功能,從the itertools recipe頁面獲得powerset:
from itertools import chain, combinations
def powerset(iterable):
"""
powerset([1,2,3]) -->() (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
"""
xs = list(iterable)
# note we return an iterator rather than a list
return chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1))
一樣使用:
>>> list(powerset("abc"))
[(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]
>>> list(powerset(set([1,2,3])))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
地圖設置,如果你想使您可以使用集,交集,等...:
>>> map(set, powerset(set([1,2,3])))
[set([]), set([1]), set([2]), set([3]), set([1, 2]), set([1, 3]), set([2, 3]), set([1, 2, 3])]
>>> reduce(lambda x,y: x.union(y), map(set, powerset(set([1,2,3]))))
set([1, 2, 3])
`scipy.misc.comb(S,m)`給出你將得到的子集的數量。由於S的m大小子集的數量非常大,因此最終應在執行代碼之前進行檢查。 – 2015-02-20 17:19:35
字面上有同樣的問題,開始自己編寫代碼,然後意識到必須存在一個Python庫! – 2016-11-10 18:23:28