简体   繁体   English

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

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

I have a bunch of items which have been sorted in different sets.我有一堆物品,它们被分类成不同的集合。 These sets might have not null intersection between them.这些集合之间可能没有 null 交集。 How can I find all the sets that are not contained in any of the existing sets?我怎样才能找到不包含在任何现有集合中的所有集合?

For example:例如:

  • items: a,b,c,d项目:a,b,c,d

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

In this case the result should be: {a}, {b,d,c}在这种情况下,结果应该是:{a}, {b,d,c}

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

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

My approach would be to create a graph with:我的方法是创建一个图表:

  • nodes are the sets节点是集合
  • there is an edege between set 1 and set 2 if set 1 is contained in set 2如果集合 1 包含在集合 2 中,则集合 1 和集合 2 之间存在边

Once I build the graph the solution will be the edges without predecessors (or incoming edges).一旦我构建了图形,解决方案将是没有前任的边(或传入边)。

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])

Here are two other ways without networkx :这里有另外两种没有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)

or或者

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 for Output 为

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

is

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

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

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