Can somebody explain what does this 'nx.connected_components()' does?

Viewed 2572

I have got some code from git and i was trying to understand it, here's a part of it, i didn't understand the second line of this code

G = nx.Graph(network_map)  # Graph for the whole network
components = list(nx.connected_components(G))

Whats does this function connected_components do? I went through the documentation and couldn't understand it properly.

1 Answers

nx.connected_components(G) will return "A generator of sets of nodes, one for each component of G". A generator in Python allows iterating over values in a lazy manner (i.e., will generate the next item only when necessary).

The documentation provides the following example:

>>> import networkx as nx
>>> G = nx.path_graph(4)
>>> nx.add_path(G, [10, 11, 12])
>>> [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)]
[4, 3]

Let's go through it:

G = nx.path_graph(4) - create the directed graph 0 -> 1 -> 2 -> 3

nx.add_path(G, [10, 11, 12]) - add to G: 10 -> 11 -> 12

So, now G is a graph with 2 connected components.

[len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)] - list the sizes of all connected components in G from the largest to smallest. The result is [4, 3] since {0, 1, 2, 3} is of size 4 and {10, 11, 12} is of size 3.

So just to recap - the result is a generator (lazy iterator) over all connected components in G, where each connected component is simply a set of nodes.

Related