python - 生成满足二元关系的子集的算法

标签 python algorithm subset

我正在 python 中寻找一个合理的算法(嗯,因为我在 python 中实现了相当复杂的数学对象,所以我无法更改语言)来实现以下目标:

I am given a reflexive, symmetric binary relation bin_rel on a set X. The requested function maximal_compatible_subsets(X, bin_rel) should return all containmentwise maximal subsets of X such that the binary relation holds for all pairs a,b of elements in X.

更详细地说:假设我得到了一组对象的二元关系,比如说

def bin_rel(elt1,elt2):
    # return True if elt1 and elt2 satisfy the relation and False otherwise
    # Example: set intersection, in this case, elt1 and elt2 are sets
    # and the relation picks those pairs that have a nonempty intersection
    return elt1.intersection(elt2)

我还可以假设关系bin_rel自反(即,binary_rel(a,a) is True成立)并且<强>对称(即binary_rel(a,b) 是binary_rel(b,a) 成立)。

我现在得到了一个集合X和一个函数bin_rel,如上所述,并寻求一种有效的算法来获得所需的X子集

例如,在上面的集合交集的情况下(为了便于阅读,将集合替换为列表):

> X = [ [1,2,3], [1,3], [1,6], [3,4], [3,5], [4,5] ]
> maximal_compatible_subsets(X,bin_rel)
[[[1,2,3],[1,3],[1,6]], [[1,2,3],[1,3],[3,4],[3,5]], [[3,4],[3,5],[4,5]]]

这个问题似乎并不是很奇特,因此最受欢迎的是指向有效的现有代码片段的指针。

最佳答案

正如 Matt Timmermans 所说,这是 finding maximal cliques problem可以通过 Bron–Kerbosch algorithm 解决。 NetworkX 有 implementation可用于 Python。

关于python - 生成满足二元关系的子集的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40422434/

相关文章:

Python 2.7 - 如何以编程方式从 stdin 读取二进制数据

python - 如何乘以 Pandas 数据框并保留行键

python - Pickle 转储和时间戳与预期不符

数据库算法缩放

r - 从列表列表中选择子列表

python - 如何将 VBscript 转换为 Python 代码?

algorithm - Bumptop - 与物理学有什么关系

python - 代码战斗 : Dijkstra's Algorithm implementation

R for循环索引问题

算法 - 动态规划 - 两个数组的子集和