The largest loosely coupled component on the networkX

I have two questions.

  • In an undirected graph, I want to find the largest related component. And I read the networkX APIs, finding this function nx.connected_component_subgraphs(). But I do not know how to use it, since its return value is a generator, and I cannot get a subgraph of the largest connected component.

  • This is the same as one. But the schedule is directed. And I want to find the largest loosely coupled component of a directed graph. Therefore, I use nx.weakly_connected_component_subgraphs()this function. Question 1 has the same problem.

How can I use the built-in function in networkX to find the largest connected component in an undirected graph and the largest loosely connected component in an oriented graph?

I am using NetworkX 1.9.1.

+4
source share
1 answer

NetworkX component functions return Python generators. You can create a list of elements in a generator using the Python function list. Here is an example showing this, as well as finding the largest loosely coupled component.

In [1]: import networkx as nx

In [2]: G = nx.DiGraph()

In [3]: G.add_path([1,2,3,4])

In [4]: G.add_path([10,11,12])

You can use for example. to include the generator in the list of subgraphs:

In [5]: list(nx.weakly_connected_component_subgraphs(G))
Out[5]: 
[<networkx.classes.digraph.DiGraph at 0x278bc10>,
 <networkx.classes.digraph.DiGraph at 0x278ba90>]

The max operator takes a key argument that you can specify for a Python function lenthat calls len (g) on ​​each subgraph to calculate the number of nodes. Thus, to get the component with the most nodes, you can write

In [6]: largest = max(nx.weakly_connected_component_subgraphs(G),key=len)

In [7]: largest.nodes()
Out[7]: [1, 2, 3, 4]

In [8]: largest.edges()
Out[8]: [(1, 2), (2, 3), (3, 4)]
+4
source

All Articles