寻找最大集团并删除节点?



我正在尝试为一组项目找到最大集团。

目前我正在使用python的networkx库并使用find_cliques((函数来查找所有最大集团,如下所示:

import newtworkx as nx
G = nx.Graph()
E = [[1,2], [1,3], [1,4], [2,3], [2,4], [3,4], [2,6], [2,5], [5,6]]
G.add_edges_from(E)
#G.edges()
lst = list(nx.find_cliques(G))
lst
Out [] : [[2, 1, 3, 4], [2, 5, 6]]

但我实际上期望的是找到最大集团,然后删除最大集团图中的节点,然后再次从先前删除后留下的节点中找到最大集团。

对于上面的例子,我希望得到 [2, 1, 3, 4] 然后删除这些节点,所以只剩下 5 和 6,这将是另一个集团 [5, 6]。

更新

我们可以使用G.remove_node((,它按预期删除节点以及所有相邻的边缘。

G = nx.Graph()
E = [[1,2], [1,3], [1,4], [2,3], [2,4], [3,4], [2,6], [2,5], [5,6], [3,5], [5,7]]
G.add_edges_from(E)
list1 = list(nx.find_cliques(G))
#list1   gives [[2, 3, 1, 4], [2, 3, 5], [2, 6, 5], [7, 5]]
n = nx.number_of_nodes(G)
#n
[G.remove_node(nd) for nd in list1[0]]
list2 = list(nx.find_cliques(G))
#list2    gives [[5, 6], [5, 7]]
[G.remove_node(nd) for nd in list2[0]]
list3 = list(nx.find_cliques(G))
#list3    gives [[7]]

但是每次删除节点时,都会找到新的最大集团并将其存储在新列表中,依此类推。如何在 while 循环中运行它,直到图 G 中没有边,即节点数为 0 或 1。

您可以使用G.remove_node从图形中删除节点(以及关联的边(。

如何删除第一个集团的所有节点:

lst = list(nx.find_cliques(G))
[G.remove_node(nd) for nd in lst[0]]

要重复删除第一个集团的节点,直到没有留下任何集团:

lst = list(nx.find_cliques(G))
while len(lst) > 0:
[G.remove_node(nd) for nd in lst[0]]
lst = list(nx.find_cliques(G))

请注意,这与在每一步删除任何最大集团中的所有节点不同,这将是:

lst = list(nx.find_cliques(G))
while len(lst) > 0:
# This flattens the list of cliques into one list. `set` reduces to unique values.
flattened = set([nd for cl in lst for nd in cl])
[G.remove_node(nd) for nd in flattened]
lst = list(nx.find_cliques(G))

最后,如果您想删除集团的特定顺序(例如,首先是最大集团(,您可以通过相应地对lst进行排序来执行此操作:

lst = list(nx.find_cliques(G))
while len(lst) > 0:
lst.sort(key=len, reverse=True)       # Sort maximum clique to the front
[G.remove_node(nd) for nd in lst[0]]
lst = list(nx.find_cliques(G))

编辑:为了完整起见,以下是在删除集团之前存储它们的方法(根据您的评论,@Ankie(:

out = []
lst = list(nx.find_cliques(G))
while len(lst) > 0:
out.append(lst[0])
[G.remove_node(nd) for nd in lst[0]]
lst = list(nx.find_cliques(G))

作为补充说明,应该指出的是,这些操作基本上是"破坏"图G。如果以后再次需要图形并且需要很长时间才能构建,则处理图形的副本以保留原始图形是有意义的。可以像这样制作副本:

G2 = G.copy()

最新更新