python - 生成 k 大多数子集唯一的元素对

标签 python math parallel-processing combinatorics discrete-mathematics

我正在编写一个 Cuda 应用程序,它应该计算我的集合 S 的两个元素的函数。但是这对的顺序没有任何区别,所以:f(a,b) = f(b,a)

因此,我想生成最大大小为 K 的 S 的所有子集,而不在集合之间复制元素对。

换句话说,给定任意两个子集,我不希望它们的交集大于一个元素。 (这样我就可以避免多次计算这两个元素的函数)

例子:

给定 S={1,2,3,4,5,6,7,8,9}K=3,输出应该是这样的这个:

{ {1,2,3}, {1,4,5}, {1,6,7}, {1,8,9}, {2,4,6}, {2,5,7}, {2,8}, {2,7,9}, {3,4,7},
  {3,5,8}, {3,6,9}, {4,5,9} }

但输出不应该是这样的:

{ {1,2,3}, {1,4,5}, {1,6,7}, {1,8,9}, {2,4,6}, {2,5,7}, {2,6,8}, {2,7,9}, {3,4,7},
  {3,5,8}, {3,6,9}, {4,5,9} }

因为{2,4,6}{2,6,8}的交集是{2,6}

最佳答案

>>> from itertools import combinations, chain
>>> s = {1,2,3,4,5,6,7,8,9}
>>> k = 3
>>> seen = set()
>>> subset_sizes = reversed(range(2,k+1)) # [3,2] for this example. Reversed since you favor the sets with larger values of K
>>> for item in chain.from_iterable(combinations(s,i) for i in subset_sizes):
        pairs = set(combinations(item,2))
        if not pairs.intersection(seen):
            seen.update(pairs)
            print item


(1, 2, 3)
(1, 4, 5)
(1, 6, 7)
(1, 8, 9)
(2, 4, 6)
(2, 5, 7)
(3, 4, 7)
(3, 5, 6)
(2, 8)
(2, 9)
(3, 8)
(3, 9)
(4, 8)
(4, 9)
(5, 8)
(5, 9)
(6, 8)
(6, 9)
(7, 8)
(7, 9)

关于python - 生成 k 大多数子集唯一的元素对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10366313/

相关文章:

python - 如何对数据透视表上的值进行分组?

python - NumPy 是否有 unravel_index() 的反函数?

python - 为动态类型指定元类

python - 从曲率上下阈值检测点/特征 - 曲线四边形形状检测算法

math - float 学坏了吗?

multithreading - 在 Mojolicious 中同时获取数据

python - Cython Memoryview 段错误

JavaScript:四舍五入到最接近的值

multithreading - 如何在 Scala 中并行迭代 map ?

Java多播接收数据及并行处理