Wednesday, 15 October 2025

Python Coding challenge - Day 793| What is the output of the following Python Code?

 


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

500 Days Python Coding Challenges with Explanation

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (152) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (217) Data Strucures (13) Deep Learning (68) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (186) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1218) Python Coding Challenge (884) Python Quiz (342) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)