简体   繁体   中英

completely connected subgraphs from a larger graph in networkx

I have tried not to repost here, but I think my request is very simple and I am just inexperienced with network graphs. When using the networkx module in python, I would like to recover, from a connected graph, the subgraphs where all nodes are connected to each other (where the number of nodes is greater than 2). Is there a simple way to do this?

Here is my example:

A simple graph with seven nodes. Nodes 1,2,3 are shared connections, nodes 1,2,4 all share connections, and nodes 5,6,7 all share connections.

import networkx as nx
G=nx.Graph() #Make the graph
G.add_nodes_from([1,2,3,4,5,6,7]) #Add nodes, although redundant because of the line below
G.add_edges_from([(1,2),(1,3),(2,3),(1,4),(2,4),(1,5),(5,6),(5,7),(6,7)]) # Adding the edges

My desired output would be: ([1,2,3],[1,2,4],[5,6,7])

I can think of slightly laborious methods for writing this but was wondering if there was a simple inbuilt function for it.

It sounds like you want to discover the cliques in your graph. For this you could use nx.clique.find_cliques() :

>>> list(nx.clique.find_cliques(G))
[[1, 2, 3], [1, 2, 4], [1, 5], [6, 5, 7]]

nx.clique.find_cliques() returns a generator which will yield all cliques in the graph. You can filter out the cliques with fewer than three nodes using list comprehension:

>>> [g for g in nx.clique.find_cliques(G) if len(g) > 2]
[[1, 2, 3], [1, 2, 4], [6, 5, 7]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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