【问题标题】:Calculate product between sets, keeping only products without repeated items计算集合之间的产品,只保留没有重复项目的产品
【发布时间】:2018-01-27 22:14:00
【问题描述】:

我有一个类似于[{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}] 的集合列表,我需要计算这些集合之间的乘积,但只保留不会产生重复数字的解。我找到了一个使用itertools.product 的解决方案,但这仍然计算所有的产品,我想知道是否有一个内置方法可以立即产生我想要的东西(或者如果你有一个操作的建议加速计算时间的数据结构被广泛接受)。

我的解决方案:

from itertools import product

def pick(sets):
    for p in product(*sets):
        if len(set(p)) == len(p):
            yield p

这会导致所需的输出:

>>> x = [{i, i+1} for i in range(5)]
>>> for p in pick(x):
...     print(p)
...
(0, 1, 2, 3, 4)
(0, 1, 2, 3, 5)
(0, 1, 2, 4, 5)
(0, 1, 3, 4, 5)
(0, 2, 3, 4, 5)
(1, 2, 3, 4, 5)

【问题讨论】:

    标签: python set cartesian-product


    【解决方案1】:
    def pick(sets, excluding=frozenset()):
        if not sets:
            yield ()
            return
        for x in sets[0] - excluding:
            for rest in pick(sets[1:], excluding | {x}):
                yield (x,) + rest
    

    【讨论】:

    • 我建议def pick(sets, excluding=frozenset()):
    • 哇,就是这么简单。您认为迭代方法可行吗?我看到 itertools.product 没有递归定义。
    猜你喜欢
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    相关资源
    最近更新 更多