Python 寻找最大团和删除节点?

Python 寻找最大团和删除节点?,python,pandas,numpy,graph,clique,Python,Pandas,Numpy,Graph,Clique,我试图找到一组项目的最大派系 目前,我正在使用python的networkx库,并使用find_cliques()函数查找所有最大的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))

我试图找到一组项目的最大派系

目前,我正在使用python的networkx库,并使用find_cliques()函数查找所有最大的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):

另外需要指出的是,这些操作基本上是“销毁”图形
G
。如果以后再次需要图形,并且需要很长的时间来构建,则有必要创建图形的副本,以便保留原始图形。可以这样制作副本:

G2 = G.copy()

轻微的混乱:据我所知,删除
[2,1,3,4]
仍然会留下
[5,6]
,这在技术上是一个小集团。@WhoIsJack,对不起,我的坏朋友。您已经编辑了该部分。如何
[G.删除lst[0]中nd的节点(nd)]
删除节点?接下来,另一个调用
list(nx.find_cliques(G))
返回示例数据的
[[5,6]]
,正如预期的那样。@WhoIsJack是这样的,但是在删除节点时,它还应该从我要删除的节点列表中删除包含任何一个节点的所有边,即[2,1,3,4],因此,它将删除[5,6]以外的所有边,然后作为另一个集团返回[5,6]。虽然上面的for循环返回none,但我认为这正是这里发生的事情。从
图形的docstring.remove_node
“删除节点n和所有相邻边。”
@WholsJack谢谢,我计算出While循环,在删除之前存储最大团,即lst[0]有点混乱。为此,我们可以在while语句之后添加一个存储lst[0]的列表a1,然后继续追加它。
G2 = G.copy()