Code Explanation:
Import the Library
import networkx as nx
networkx is a Python library used for creating, analyzing, and visualizing graphs (networks).
It can represent relationships between nodes — like people in a social network or cities connected by roads.
In short: nx is the alias for NetworkX to make commands shorter.
Create an Empty Graph Object
G = nx.Graph()
nx.Graph() creates an empty, undirected graph named G.
At this point, there are:
0 nodes
0 edges
Think of G as a blank network where you’ll soon add connections.
Add Edges (Connections Between Nodes)
G.add_edges_from([(1,2), (2,3)])
.add_edges_from() takes a list of tuples, where each tuple (a, b) represents an edge between node a and node b.
Here:
(1, 2) connects node 1 to node 2
(2, 3) connects node 2 to node 3
After this line:
Nodes: {1, 2, 3}
Edges: {(1, 2), (2, 3)}
Note: NetworkX automatically adds any missing nodes when you add edges.
Count the Number of Edges
print(G.number_of_edges())
.number_of_edges() returns the total count of edges currently in the graph G.
Since we added two edges — (1,2) and (2,3) — it prints:
Output:
2
.png)

0 Comments:
Post a Comment