繁体   English   中英

如何找到不包含在任何其他集合中的所有最小集合

[英]How to find all the smallest sets not contained in any other set

我有一堆物品,它们被分类成不同的集合。 这些集合之间可能没有 null 交集。 我怎样才能找到不包含在任何现有集合中的所有集合?

例如:

  • 项目:a,b,c,d

  • 集合:{a,b,c}, {a, b}, {a}, {a,b,c,d}, {b,d,c}

在这种情况下,结果应该是:{a}, {b,d,c}

  • {a,b,c,d} 包含 {a,b,c} 包含 {a, b} 包含 {a}

  • {a,b,c,d} 包含 {b,d,c}

我的方法是创建一个图表:

  • 节点是集合
  • 如果集合 1 包含在集合 2 中,则集合 1 和集合 2 之间存在边

一旦我构建了图形,解决方案将是没有前任的边(或传入边)。

G=nx.DiGraph()

G.add_nodes_from([frozenset({'a', 'b', 'c'}),frozenset({'a', 'b'}), frozenset({'a'}), frozenset({'a', 'b', 'c', 'd'}), frozenset({'b', 'd', 'c'})])

G.add_edges_from([(n, m) for n in G for m in G if n!=m if n<m])

print([n for n, in_degree in G.in_degree() if in_degree == 0])

这里有另外两种没有networkx的方法:

sorted_sets = sorted(sets, key=len, reverse=True)
minimal = []
while sorted_sets:
    s = sorted_sets.pop()
    for m in minimal:
        if m <= s:
            break
    else:
        minimal.append(s)

或者

frozen_sets = {frozenset(s) for s in sets}
minimal= set()
while frozen_sets:
    s = frozen_sets.pop()
    remove = set()
    for m in minimal:
        if m <= s:
            break
        elif s < m:
            remove.add(m)
    else:
        minimal.add(s)
        minimal -= remove

Output 为

sets = [{"a", "b", "c"}, {"a", "b"}, {"a"}, {"a", "b", "c", "d"}, {"b", "d", "c"}]

[{'a'}, {'c', 'd', 'b'}]
{frozenset({'a'}), frozenset({'c', 'd', 'b'})}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM