data princess
data princess

Reputation: 1158

Calculating the number of disconnected components of a NetworkX graph

Starting with a randomly generated tree, I want to consider each node of the tree and potentially remove it with some probability p. Since trees have no cycles and there is a unique path between any pair of nodes, the removal of a node should leave d disconnected trees in its wake, where d is the degree of that node.

My question is, once I've done this for the whole graph, how can I check how many of these unconnected segments there are?

import networkx as nx
import random as rand

n = 20
p = 0.1

G = nx.random_tree(n)
for i in range(0, n):
    if rand.random() < p:
        G.remove_node(i)

x = G.count_disconnected_components() # is there anything that accomplishes this?

For example, for this graph, G.count_disconnected_components() should return 3. graph with three unconnected components

Upvotes: 5

Views: 3314

Answers (1)

Felix
Felix

Reputation: 1905

It seems to me you actually want to count the number of connected parts. Try number_connected_components:

print(list(nx.connected_components(G)))
print(nx.number_connected_components(G))

Upvotes: 5

Related Questions