Python:带有生成器的给定集合的幂集

2022-01-17 00:00:00 python generator algorithm set powerset

问题描述

我正在尝试使用 generators 在 Python 中构建给定集合的子集列表.说我有

I am trying to build a list of subsets of a given set in Python with generators. Say I have

set([1, 2, 3])

作为输入,我应该有

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

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

as output. How can I achieve this?


解决方案

最快的方法是使用itertools,尤其是chain和combinations:

The fastest way is by using itertools, especially chain and combinations:

>>> 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 并将元组转换为集合:

If you need a generator just use yield and turn tuples into sets:

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])
>>> 

相关文章