python - 计算集合之间的乘积,仅保留不重复项的乘积

标签 python set cartesian-product

我有一个类似于 [{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)

最佳答案

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

关于python - 计算集合之间的乘积,仅保留不重复项的乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45769967/

相关文章:

PHP SimpleXML,如何设置属性?

java - 为什么 Collections.synchronizedSet(HashSet) 对于 addAll、retainAll 和 contains 比 HashSet 更快?

python - 为什么 `myfloat in myset` 变得 super 慢?

python - 不同大小的笛卡尔积

dictionary - Racket 映射笛卡尔积事物

python - Django包生成随机字母数字字符串

python - 使用 python centos-7 安装 theano

python - 如何在 babel.dates.format_date 中将格式设置为小时?

python - DataFrame Python 中的数学求值字符串

r - R中代数关系的笛卡尔积表