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))
这里有一行代码,它给出整数的所有子集[0..n],而不仅仅是给定长度的子集:
所以例如
使用规范函数从the itertools recipe页获取powerset:
使用方式:
如果需要,映射到集合,以便可以使用并集、交叉点等:
如果你有Python2.6或更高版本,那么itertools.combinations就是你的朋友。否则,请检查链接以获取等效函数的实现。
S:要查找其子集的集合
m: 子集中的元素数
相关问题 更多 >
编程相关推荐