Centrality measures and shortest path
Goal: Analysing a well-known social graph.
import networkx as nx
G = nx.karate_club_graph()
print("Nodes and edges:", G.number_of_nodes(), G.number_of_edges())
bc = nx.betweenness_centrality(G)
top = sorted(bc, key=bc.get, reverse=True)[:3]
print("Highest betweenness:", [(n, round(bc[n], 3)) for n in top])
print("Shortest path 0→33:", nx.shortest_path(G, 0, 33))
print("Number of communities (Louvain):", len(nx.community.louvain_communities(G, seed=0)))
Code explanation
Zachary's karate club graph ships with NetworkX. We compute degree and betweenness centrality and find a shortest path. These measures are also used as node features before graph neural networks.
Output recorded during testing
Nodes and edges: 34 78 Highest betweenness: [(0, 0.438), (33, 0.304), (32, 0.145)] Shortest path 0→33: [0, 8, 33] Number of communities (Louvain): 4
This example was actually run and tested on 21 November 2026 on a CPU — networkx 3.7, python 3.13.18
