Finding maximal cliques and removing nodes?

五迷三道 提交于 2019-12-06 16:14:49

You can use G.remove_node to remove the nodes (and the associated edges) from your graph.

How to remove all nodes of the first clique:

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

To repeatedly remove the nodes of the first clique, until no cliques are left:

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

Note that this is not the same as removing all nodes that are in any maximal clique at each step, which would be:

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

Finally, if there is a certain order in which you would like to remove cliques (e.g. the maximum clique first), you could do this by sorting lst accordingly:

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

Edit: for completeness sake, here's how one could store the cliques before deleting them (as per your comment, @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))

As an additional note it should be pointed out that these operations basically 'destroy' graph G. If the graph is needed again later on and takes a long time to construct, it makes sense to work on a copy of the graph so that the original is preserved. A copy can be made like this:

G2 = G.copy()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!