Python:使用生成器的给定集合的powerset

时间:2013-09-16 11:13:57

标签: python algorithm set generator powerset

我正在尝试使用生成器在Python中构建给定集合的子集列表。说我有

set([1, 2, 3])

作为输入,我应该

[set([1, 2, 3]), set([2, 3]), set([1, 3]), set([3]), set([1, 2]), set([2]), set([1]), set([])]

作为输出。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:18)

最快的方法是使用itertools,尤其是链和组合:

>>> from itertools import chain, combinations
>>> i = set([1, 2, 3])
>>> for z in chain.from_iterable(combinations(i, r) for r in range(len(i)+1)):
    print z 
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)
>>> 

如果你需要一个生成器,只需使用yield并将元组转换为集合:

def powerset_generator(i):
    for subset in chain.from_iterable(combinations(i, r) for r in range(len(i)+1)):
        yield set(subset)

然后简单地说:

>>> for i in powerset_generator(i):
    print i


set([])
set([1])
set([2])
set([3])
set([1, 2])
set([1, 3])
set([2, 3])
set([1, 2, 3])
>>> 

答案 1 :(得分:8)

来自itertools文档的recipes部分:

def powerset(iterable):
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))