0% found this document useful (0 votes)
21 views102 pages

Graph Theroy Practical

The document contains Python code snippets using the NetworkX library to create and analyze various types of graphs, including regular graphs, directed graphs, bipartite graphs, and trees. It covers tasks such as checking graph properties (connectedness, bipartiteness, Eulerian paths), visualizing graphs with Matplotlib, and calculating metrics like degrees, eccentricity, and connectivity. Each section includes specific graph examples and visual outputs to illustrate the concepts discussed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views102 pages

Graph Theroy Practical

The document contains Python code snippets using the NetworkX library to create and analyze various types of graphs, including regular graphs, directed graphs, bipartite graphs, and trees. It covers tasks such as checking graph properties (connectedness, bipartiteness, Eulerian paths), visualizing graphs with Matplotlib, and calculating metrics like degrees, eccentricity, and connectivity. Each section includes specific graph examples and visual outputs to illustrate the concepts discussed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

Slip 1 ❗️

Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Regular graph on 4 vertices with degree 2


G1 = nx.Graph()
G1.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1)]) # Cycle of 4 vertices
plt.figure(figsize=(4, 3))
nx.draw(G1, with_labels=True, node_color='lightblue')
plt.title("a) Regular Graph (4 vertices, degree 2)")
plt.show()

# b) Symmetric directed graph on 6 vertices


G2 = nx.DiGraph()
edges = [(1,2), (2,1), (3,4), (4,3), (5,6), (6,5)] # Pairs with reverse edges
G2.add_edges_from(edges)
plt.figure(figsize=(4, 3))
nx.draw(G2, with_labels=True, node_color='lightgreen', arrows=True)
plt.title("b) Symmetric Directed Graph (6 vertices)")
plt.show()

# c) Union of Graph G1 and G2


G3_1 = nx.Graph()
G3_1.add_edges_from([(1,2), (2,3), (3,4), (4,5)])

G3_2 = nx.Graph()
G3_2.add_edges_from([('a','b'), ('b','c'), ('c','d'), ('b','d')])

G_union = nx.compose(G3_1, G3_2) # Combine both graphs


plt.figure(figsize=(5, 4))
nx.draw(G_union, with_labels=True, node_color='orange')
plt.title("c) Union of Graph G1 and G2")
plt.show()

Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Complete graph with 6 red vertices & node size 700


G1 = nx.complete_graph(6)
plt.figure(figsize=(4, 3))
nx.draw(G1, with_labels=True, node_color='red', node_size=700)
plt.title("a) Complete Graph with 6 Red Vertices")
plt.show()

# b) Check if G is bipartite
G2 = nx.Graph()
G2.add_edges_from([(1, 2), (1, 3), (4, 3), (5, 1), (4, 5), (3, 5)])
is_bipartite = nx.is_bipartite(G2)
print("b) Is the graph bipartite?", is_bipartite)
plt.figure(figsize=(4, 3))
nx.draw(G2, with_labels=True, node_color='lightblue')
plt.title("b) Graph to Check Bipartiteness")
plt.show()

# c) Graph with 6 labelled vertices and 10 labelled edges


G3 = nx.Graph()
G3.add_edges_from([(1,2), (1,3), (1,4), (2,3), (2,5), (3,5), (3,6), (4,5),
(4,6), (5,6)])
pos = nx.spring_layout(G3)
plt.figure(figsize=(5, 4))
nx.draw(G3, pos, with_labels=True, node_color='violet',
node_size=600)
nx.draw_networkx_edge_labels(G3, pos, edge_labels={(u, v):
f"{u}-{v}" for u, v in G3.edges()})
plt.title("c) Graph with 6 Vertices & 10 Labelled Edges")
plt.show()

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Handshaking Lemma for star graph on 7 vertices


G1 = nx.star_graph(6) # 1 center + 6 outer = 7 vertices
degrees = [d for n, d in G1.degree()]
sum_degrees = sum(degrees)
num_edges = G1.number_of_edges()
print("a) Handshaking Lemma Verification")
print("Sum of degrees:", sum_degrees)
print("2 × Number of edges:", 2 * num_edges)
print("Handshaking Lemma Verified?" , sum_degrees == 2 *
num_edges)
plt.figure()
nx.draw(G1, with_labels=True, node_color='lightcoral')
plt.title("a) Star Graph with 7 Vertices")
plt.show()

# b) Draw Petersen Graph and check if it's 2 or 3 regular


G2 = nx.petersen_graph()
deg_set = set(dict(G2.degree()).values())
regularity = f"{list(deg_set)[0]}-regular" if len(deg_set) == 1 else "Not
regular"
print("\nb) Petersen Graph is:", regularity)
plt.figure()
nx.draw(G2, with_labels=True, node_color='lightgreen')
plt.title("b) Petersen Graph")
plt.show()

# c) Balanced binary tree of height 4 with labelled vertices and


edges
G3 = nx.balanced_tree(r=2, h=4)
pos = nx.spring_layout(G3)
plt.figure(figsize=(8, 5))
nx.draw(G3, pos, with_labels=True, node_color='lightblue',
node_size=500)
nx.draw_networkx_edge_labels(G3, pos, edge_labels={(u, v):
f"{u}-{v}" for u, v in G3.edges()})
plt.title("c) Balanced Binary Tree (Height 4)")
plt.show()
Slip 2 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Graph G with given vertices and edges


G = nx.Graph()
G.add_edges_from([(1,5), (1,3), (2,3), (2,4), (3,4), (4,5)])
plt.figure()
nx.draw(G, with_labels=True, node_color='lightpink')
plt.title("a) Graph G")
plt.show()

# b) Degree of each vertex and check if G is connected


degrees = dict(G.degree())
print("b) Degrees of all vertices:")
for node, deg in degrees.items():
print(f"Vertex {node}: Degree {deg}")
is_connected = nx.is_connected(G)
print("Is the graph connected?", is_connected)

# c) Cycle graph C12 with blue color and node size 800
C12 = nx.cycle_graph(12)
plt.figure()
nx.draw(C12, with_labels=True, node_color='blue', node_size=800)
plt.title("c) Cycle Graph C12")
plt.show()
Q.2

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# a) Draw intersection of G1 and G2


G1 = nx.Graph()
G1.add_edges_from([(1,2), (2,3), (3,4), (4,5), (1,4)])

G2 = nx.Graph()
G2.add_edges_from([('a','b'), ('b','c'), ('c','d'), ('b','d'), ('a','c')])
G_intersection = nx.intersection(G1, G2)
plt.figure()
nx.draw(G_intersection, with_labels=True, node_color='lightgray')
plt.title("a) Intersection of G1 and G2 (Empty Graph)")
plt.show()

# b) Eccentricity of each vertex in G1


ecc = nx.eccentricity(G1)
print("b) Eccentricity of each vertex in G1:")
for node, e in ecc.items():
print(f"Vertex {node}: Eccentricity = {e}")

# c) Adjacency and Incidence matrices of G2


print("\nc) Adjacency Matrix of G2:")
adj_matrix = nx.adjacency_matrix(G2).todense()
print(adj_matrix)

print("\nIncidence Matrix of G2:")


nodes = list(G2.nodes())
edges = list(G2.edges())
inc_matrix = np.zeros((len(nodes), len(edges)), dtype=int)
for j, (u, v) in enumerate(edges):
i1 = nodes.index(u)
i2 = nodes.index(v)
inc_matrix[i1][j] = 1
inc_matrix[i2][j] = 1
print(inc_matrix)

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Complete Bipartite Graphs K4,3 and K5,9


K1 = nx.complete_bipartite_graph(4, 3)
plt.figure()
nx.draw(K1, with_labels=True, node_color='skyblue')
plt.title("a) Complete Bipartite Graph K4,3")
plt.show()

K2 = nx.complete_bipartite_graph(5, 9)
plt.figure()
nx.draw(K2, with_labels=True, node_color='orange')
plt.title("a) Complete Bipartite Graph K5,9")
plt.show()

# b) Any connected graph G and check if it is a tree


G = nx.Graph()
G.add_edges_from([(1,2), (1,3), (2,4), (3,5)])
is_tree = nx.is_tree(G)
plt.figure()
nx.draw(G, with_labels=True, node_color='lightgreen')
plt.title(f"b) Graph G (Tree? {is_tree})")
plt.show()
print("b) Is G a tree?", is_tree)

# c) Check if graph G is Eulerian


G2 = nx.Graph()
G2.add_edges_from([('p','q'), ('q','r'), ('r','s'), ('p','s')])
plt.figure()
nx.draw(G2, with_labels=True, node_color='lightblue')
plt.title("c) Graph G for Eulerian Check")
plt.show()
is_eulerian = nx.is_eulerian(G2)
print("c) Is G Eulerian?", is_eulerian)
Slip 3 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Null graph on 12 red vertices with size 600


G_null = nx.empty_graph(12)
plt.figure()
nx.draw(G_null, with_labels=True, node_color='red', node_size=600)
plt.title("a) Null Graph with 12 Vertices")
plt.show()

# b) Any asymmetric directed graph on 10 vertices


G_asym = nx.DiGraph()
G_asym.add_edges_from([(0, 1), (1, 2), (2, 3), (4, 0), (5, 6), (6, 7), (8,
9)])
plt.figure()
nx.draw(G_asym, with_labels=True, node_color='lightblue',
arrows=True)
plt.title("b) Asymmetric Directed Graph (10 Vertices)")
plt.show()

# c) Ternary trees (height 1 and 3)


# Height 1
T1 = nx.balanced_tree(r=3, h=1)
plt.figure()
nx.draw(T1, with_labels=True, node_color='violet')
plt.title("c) Ternary Tree of Height 1")
plt.show()
# Height 3
T3 = nx.balanced_tree(r=3, h=3)
plt.figure(figsize=(10, 6))
nx.draw(T3, with_labels=True, node_color='orchid')
plt.title("c) Ternary Tree of Height 3")
plt.show()

Q.2

import networkx as nx
import matplotlib.pyplot as plt

# Define the graph G


G = nx.Graph()
G.add_edges_from([(1,3), (3,5), (5,6), (6,4), (4,2), (2,1)])

# Draw the graph


plt.figure()
nx.draw(G, with_labels=True, node_color='lightcoral')
plt.title("Graph G")
plt.show()

# a) Vertex connectivity and edge connectivity


vertex_conn = nx.node_connectivity(G)
edge_conn = nx.edge_connectivity(G)
print("a) Vertex Connectivity:", vertex_conn)
print("a) Edge Connectivity:", edge_conn)

# b) Center, radius, and diameter


center = nx.center(G)
radius = nx.radius(G)
diameter = nx.diameter(G)
print("b) Center of G:", center)
print("b) Radius of G:", radius)
print("b) Diameter of G:", diameter)

# c) Complete bipartite graph K2,8


K2_8 = nx.complete_bipartite_graph(2, 8)
plt.figure()
nx.draw(K2_8, with_labels=True, node_color='lightblue')
plt.title("c) Complete Bipartite Graph K2,8")
plt.show()

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# Define the graph G1


G1 = nx.Graph()
G1.add_edges_from([('a', 'b'), ('c', 'd'), ('a', 'e'), ('b', 'f'), ('a', 'f')])

# a) Check if G1 is a connected graph


is_connected = nx.is_connected(G1)
print("a) Is the graph G1 connected?", is_connected)

# b) Draw the complement of G1 and check if it is a simple graph


G1_complement = nx.complement(G1)
plt.figure()
nx.draw(G1_complement, with_labels=True, node_color='lightgreen')
plt.title("b) Complement of Graph G1")
plt.show()
# Check if complement is a simple graph (no multiple edges or
loops)
is_simple = nx.is_simple_path(G1_complement)
print("b) Is the complement of G1 a simple graph?", is_simple)

# c) Find the number of vertices, edges, and degrees of all


vertices in above graph G1
num_vertices = G1.number_of_nodes()
num_edges = G1.number_of_edges()
degrees = dict(G1.degree())

print("c) Number of vertices:", num_vertices)


print("c) Number of edges:", num_edges)
print("c) Degrees of all vertices:", degrees)
Slip 4 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Generate graph G with vertex set {v, w, x, y, z} and the given


edge set
G = nx.Graph()
G.add_edges_from([('v', 'w'), ('x', 'y'), ('w', 'z'), ('v', 'z'), ('x', 'z')])

plt.figure()
nx.draw(G, with_labels=True, node_color='lightblue', node_size=700,
font_size=12)
plt.title("a) Graph G with labeled vertices and edges")
plt.show()

# b) Find the number of components in the graph G


num_components = nx.number_connected_components(G)
print("b) Number of components in G:", num_components)

# c) Delete edge e1 (v, w) and e4 (v, z)


G.remove_edge('v', 'w')
G.remove_edge('v', 'z')

plt.figure()
nx.draw(G, with_labels=True, node_color='lightgreen',
node_size=700, font_size=12)
plt.title("c) Graph G after deleting edges e1 and e4")
plt.show()
Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Draw any connected graph G and determine if it is a


Hamiltonian graph
G = nx.Graph()
G.add_edges_from([(1, 2), (1, 3), (2, 3), (2, 4), (3, 5), (4, 5)])

# Draw the connected graph


plt.figure()
nx.draw(G, with_labels=True, node_color='lightcoral', node_size=700)
plt.title("a) Connected Graph G")
plt.show()

# Check if G is a Hamiltonian graph (using nx.hamiltonian_path


function)
hamiltonian = nx.is_hamiltonian(G)
print("a) Is the graph Hamiltonian?", hamiltonian)

# b) Draw a 4-ary tree of height 4


T = nx.balanced_tree(r=4, h=4)

plt.figure(figsize=(12, 8))
nx.draw(T, with_labels=True, node_color='lightgreen', node_size=700,
font_size=10)
plt.title("b) 4-ary Tree of Height 4")
plt.show()

# c) Find all bridges and cut vertices in a graph with 6 vertices


and 6 edges
G2 = nx.Graph()
G2.add_edges_from([(1, 2), (1, 3), (2, 3), (3, 4), (4, 5), (4, 6)])

# Draw the graph G2


plt.figure()
nx.draw(G2, with_labels=True, node_color='lightblue', node_size=700)
plt.title("c) Graph G2 (6 vertices, 6 edges)")
plt.show()

# Find bridges and cut vertices in the graph G2


bridges = list(nx.bridges(G2))
cut_vertices = list(nx.articulation_points(G2))

print("c) Bridges in G2:", bridges)


print("c) Cut vertices in G2:", cut_vertices)

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Draw wheel graphs W10 and W18 with blue-colored vertices


W10 = nx.wheel_graph(10)
W18 = nx.wheel_graph(18)

# Draw W10 graph


plt.figure()
nx.draw(W10, with_labels=True, node_color='blue', node_size=700,
font_size=12)
plt.title("a) Wheel Graph W10")
plt.show()
# Draw W18 graph
plt.figure()
nx.draw(W18, with_labels=True, node_color='blue', node_size=700,
font_size=12)
plt.title("a) Wheel Graph W18")
plt.show()

# b) Draw K5 and H = complement of N5. Check if K5 is


isomorphic to H
K5 = nx.complete_graph(5)
N5 = nx.Graph()
N5.add_nodes_from([1, 2, 3, 4, 5])
N5.add_edges_from([(1, 2), (1, 3), (2, 4), (3, 5)])

# Complement of N5
H = nx.complement(N5)

# Draw K5
plt.figure()
nx.draw(K5, with_labels=True, node_color='lightblue', node_size=700)
plt.title("b) Complete Graph K5")
plt.show()

# Draw H (complement of N5)


plt.figure()
nx.draw(H, with_labels=True, node_color='lightgreen',
node_size=700)
plt.title("b) Complement of N5 (Graph H)")
plt.show()

# Check if K5 is isomorphic to H
is_isomorphic = nx.is_isomorphic(K5, H)
print("b) Is K5 isomorphic to H?", is_isomorphic)

# c) Find the number of components in graph W10


num_components = nx.number_connected_components(W10)
print("c) Number of components in W10:", num_components)
Slip 5 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Generate graph G with vertex set {1,2,3,4,5} and edge set


G = nx.Graph()
G.add_edges_from([(4, 5), (5, 3), (2, 2), (2, 3), (2, 4), (3, 4), (1, 5)])

# Draw the graph G with vertices in red color and edges in green
plt.figure()
nx.draw(G, with_labels=True, node_color='red', edge_color='green',
node_size=700, font_size=12)
plt.title("a) Graph G with vertices in red and edges in green")
plt.show()

# b) Verify Handshaking lemma for above graph G


# Handshaking Lemma: sum of degrees of all vertices is twice
the number of edges.
degree_sum = sum(dict(G.degree()).values())
num_edges = G.number_of_edges()
print(f"b) Sum of degrees: {degree_sum}")
print(f"b) Number of edges: {num_edges}")
print(f"b) Verification of Handshaking Lemma: {degree_sum == 2 *
num_edges}")

# c) Draw a regular graph on 5 vertices with degree 3


# A regular graph with 5 vertices and degree 3 can be created
using nx.complete_graph(5)
regular_graph = nx.complete_graph(5)

plt.figure()
nx.draw(regular_graph, with_labels=True, node_color='lightblue',
node_size=700, font_size=12)
plt.title("c) Regular Graph on 5 vertices with degree 3")
plt.show()

Q.2

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# a) Create a simple graph G1


G1 = nx.Graph()
G1.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1)])

# Adjacency matrix of G1
adj_matrix = nx.adjacency_matrix(G1).todense()
print("a) Adjacency Matrix of G1:")
print(adj_matrix)

# Incidence matrix of G1
inc_matrix = nx.incidence_matrix(G1).todense()
print("a) Incidence Matrix of G1:")
print(inc_matrix)

# b) Let G2 = K4 (complete graph on 4 vertices) and G3 = N4


(cycle graph on 4 vertices)
G2 = nx.complete_graph(4) # K4
G3 = nx.cycle_graph(4) # N4

# Find the intersection of G2 and G3


intersection = nx.intersection(G2, G3)

# Draw G2 and G3
plt.figure()
nx.draw(G2, with_labels=True, node_color='lightblue', node_size=700,
font_size=12)
plt.title("b) Graph G2: Complete Graph K4")
plt.show()

plt.figure()
nx.draw(G3, with_labels=True, node_color='lightgreen',
node_size=700, font_size=12)
plt.title("b) Graph G3: Cycle Graph N4")
plt.show()

# Draw intersection graph


plt.figure()
nx.draw(intersection, with_labels=True, node_color='yellow',
node_size=700, font_size=12)
plt.title("b) Intersection of G2 and G3")
plt.show()

# c) Draw wheel graphs W21 and W30


W21 = nx.wheel_graph(21)
W30 = nx.wheel_graph(30)

# Draw W21 graph


plt.figure(figsize=(10, 10))
nx.draw(W21, with_labels=True, node_color='cyan', node_size=700,
font_size=10)
plt.title("c) Wheel Graph W21")
plt.show()

# Draw W30 graph


plt.figure(figsize=(12, 12))
nx.draw(W30, with_labels=True, node_color='pink', node_size=700,
font_size=10)
plt.title("c) Wheel Graph W30")
plt.show()

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Draw any tree T with 8 vertices and 7 edges


T = nx.Graph()
T.add_edges_from([(1, 2), (1, 3), (3, 4), (3, 5), (2, 6), (5, 7), (5, 8)])

# Draw the tree T


plt.figure()
nx.draw(T, with_labels=True, node_color='lightgreen', node_size=700,
font_size=12)
plt.title("a) Tree T with 8 vertices and 7 edges")
plt.show()

# b) Find center and radius of the tree T


center = nx.center(T)
radius = nx.radius(T)
print(f"b) Center of the tree T: {center}")
print(f"b) Radius of the tree T: {radius}")

# c) Find number of vertices and edges in the tree T


num_vertices = T.number_of_nodes()
num_edges = T.number_of_edges()
print(f"c) Number of vertices in tree T: {num_vertices}")
print(f"c) Number of edges in tree T: {num_edges}")
Slip 6 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Draw any tree T with 8 vertices and 7 edges


T = nx.Graph()
T.add_edges_from([(1, 2), (1, 3), (3, 4), (3, 5), (2, 6), (5, 7), (5, 8)])

# Draw the tree T with labeled vertices and color of your choice (I
chose lightblue for vertices and green for edges)
plt.figure()
nx.draw(T, with_labels=True, node_color='lightblue',
edge_color='green', node_size=700, font_size=12)
plt.title("a) Tree T with 8 vertices and 7 edges")
plt.show()

# b) Determine whether T is a binary tree


# A binary tree is a tree where each node has at most two
children.
# To check, we need to see if no node has a degree greater than 3
is_binary_tree = all(deg <= 3 for _, deg in T.degree())
print(f"b) Is the tree T a binary tree? {'Yes' if is_binary_tree else 'No'}")

# c) Find center, radius, and diameter of the tree T


center = nx.center(T)
radius = nx.radius(T)
diameter = nx.diameter(T)
print(f"c) Center of the tree T: {center}")
print(f"c) Radius of the tree T: {radius}")
print(f"c) Diameter of the tree T: {diameter}")

Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Generate graph G with vertex set {a, b, c, d} and edge set {(a,
b), (c, d), (a, c)}
G = nx.Graph()
G.add_edges_from([('a', 'b'), ('c', 'd'), ('a', 'c')])

# Draw graph G with vertices in red color and edges in green


plt.figure()
nx.draw(G, with_labels=True, node_color='red', edge_color='green',
node_size=700, font_size=12)
plt.title("a) Graph G with vertices in red and edges in green")
plt.show()

# b) Add vertex e and edges {(b, c), (c, d)} and check if the graph
is connected
G.add_edges_from([('b', 'c'), ('c', 'd')])

# Check if the graph is connected


is_connected = nx.is_connected(G)
print(f"b) Is the new graph G1 connected? {'Yes' if is_connected else
'No'}")
# c) Draw all paths from vertex 'a' to vertex 'd' in the new graph
G1
paths = list(nx.all_simple_paths(G, source='a', target='d'))
print(f"c) All paths from vertex 'a' to vertex 'd': {paths}")

# Draw the updated graph G1 with the new edges and vertex
plt.figure()
nx.draw(G, with_labels=True, node_color='red', edge_color='green',
node_size=700, font_size=12)
plt.title("c) Graph G1 with new vertex 'e' and edges")
plt.show()

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Draw regular graph on 6 vertices with degree 3 and label all


vertices and edges.
G = nx.Graph()
# Regular graph with 6 vertices, degree 3 (each vertex has 3 edges)
G.add_edges_from([(1, 2), (1, 3), (1, 4), (2, 5), (2, 6), (3, 5), (3, 6), (4,
5), (4, 6)])

# Draw graph with labeled vertices and edges


plt.figure()
nx.draw(G, with_labels=True, node_color='red', edge_color='green',
node_size=700, font_size=12)
plt.title("a) Regular Graph on 6 vertices with degree 3")
plt.show()
# b) Draw Petersen graph and determine if it is 2-regular or
3-regular
petersen_graph = nx.petersen_graph()

# Draw Petersen Graph


plt.figure()
nx.draw(petersen_graph, with_labels=True, node_color='blue',
edge_color='black', node_size=700, font_size=12)
plt.title("b) Petersen Graph")
plt.show()

# Check if Petersen graph is 2-regular or 3-regular (degree of


each vertex)
degree_sequence = [deg for node, deg in petersen_graph.degree()]
is_2_regular = all(deg == 2 for deg in degree_sequence)
is_3_regular = all(deg == 3 for deg in degree_sequence)

print(f"b) Petersen graph is 2-regular: {is_2_regular}, 3-regular:


{is_3_regular}")

# c) Verify Handshaking Lemma for Petersen Graph (sum of


degrees of all vertices is twice the number of edges)
handshaking_lemma = sum(degree_sequence) == 2 *
petersen_graph.number_of_edges()
print(f"c) Does the Handshaking Lemma hold for Petersen Graph?
{'Yes' if handshaking_lemma else 'No'}")
Slip 7 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Symmetric Directed Graph on 7 vertices


DG = nx.DiGraph()
edges = [(1,2), (2,1), (2,3), (3,2), (3,4), (4,3), (4,5), (5,4), (5,6), (6,5),
(6,7), (7,6)]
DG.add_edges_from(edges)
plt.figure()
nx.draw(DG, with_labels=True, node_color='lightblue',
edge_color='gray', node_size=700, font_size=12, arrowsize=20)
plt.title("a) Symmetric Directed Graph on 7 Vertices")
plt.show()

# b) Complete Bipartite Graphs


fig, axs = plt.subplots(1, 3, figsize=(15, 4))
for i, (n1, n2) in enumerate([(4, 2), (5, 6), (2, 6)]):
G = nx.complete_bipartite_graph(n1, n2)
pos = nx.bipartite_layout(G, nodes=range(n1))
nx.draw(G, pos, with_labels=True, ax=axs[i], node_color='orange',
edge_color='green', node_size=600)
axs[i].set_title(f"K{n1},{n2}")
plt.suptitle("b) Complete Bipartite Graphs")
plt.tight_layout()
plt.show()
# c) Union of K2,2 and K3,3
G1 = nx.complete_bipartite_graph(2, 2)
G2 = nx.complete_bipartite_graph(3, 3)
# Relabel nodes to avoid overlap
G2 = nx.relabel_nodes(G2, lambda x: x + 10)
G_union = nx.union(G1, G2)

plt.figure()
nx.draw(G_union, with_labels=True, node_color='lightgreen',
edge_color='blue', node_size=600)
plt.title("c) Union of K2,2 and K3,3")
plt.show()

Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Create simple graph G1


G1 = nx.Graph()
edges = [(1, 2), (2, 3), (3, 4), (4, 1), (2, 4)]
G1.add_edges_from(edges)

plt.figure(figsize=(5, 4))
nx.draw(G1, with_labels=True, node_color='skyblue',
edge_color='purple', node_size=800)
plt.title("a) Simple Graph G1")
plt.show()

# b) Check if G1 is bipartite
is_bipartite = nx.is_bipartite(G1)
print(f"b) Is G1 bipartite? {'Yes' if is_bipartite else 'No'}")

# c) Draw complement of G1 and check connectivity


G1_comp = nx.complement(G1)

plt.figure(figsize=(5, 4))
nx.draw(G1_comp, with_labels=True, node_color='lightgreen',
edge_color='red', node_size=800)
plt.title("c) Complement of G1")
plt.show()

is_connected = nx.is_connected(G1_comp)
print(f"Is the complement of G1 connected? {'Yes' if is_connected else
'No'}")

Q.3

a) Draw graph 𝐺 with blue vertices and red edges


import networkx as nx
import matplotlib.pyplot as plt

# Create graph G
G = nx.Graph()
edges = [(4,5), (5,3), (2,2), (2,3), (2,4), (3,4), (1,5)]
G.add_edges_from(edges)

plt.figure(figsize=(5, 4))
nx.draw(G, with_labels=True, node_color='blue', edge_color='red',
node_size=800, font_color='white')
plt.title("Graph G")
plt.show()
b) Find adjacency and incidence matrix of graph G

# Adjacency matrix
adj_matrix = nx.adjacency_matrix(G).todense()
print("Adjacency Matrix:")
print(adj_matrix)

# Incidence matrix
inc_matrix = nx.incidence_matrix(G, oriented=False).todense()
print("\nIncidence Matrix:")
print(inc_matrix)

c) Number of vertices, number of edges, and degrees of all


vertices

print("Number of vertices:", G.number_of_nodes())


print("Number of edges:", G.number_of_edges())

print("Degrees of vertices:")
for node in G.nodes():
print(f"Vertex {node}: Degree {G.degree(node)}")
Slip 8 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# (a) Star graph on 7 vertices


G = nx.star_graph(6) # Center + 6 outer nodes

plt.figure(figsize=(6, 4))
nx.draw(G, with_labels=True, node_color='orange', node_size=600,
edge_color='black')
plt.title("Star Graph G (7 vertices)")
plt.show()

# (b) Verify Handshaking Lemma


deg_sum = sum(dict(G.degree()).values())
edges = G.number_of_edges()
print("Sum of degrees:", deg_sum)
print("2 × Number of edges:", 2 * edges)
print("Handshaking Lemma Verified:", deg_sum == 2 * edges)

# (c) Complement of G
G_comp = nx.complement(G)
plt.figure(figsize=(6, 4))
nx.draw(G_comp, with_labels=True, node_color='skyblue',
node_size=600, edge_color='green')
plt.title("Complement of G")
plt.show()
# Check if it's a simple graph (no self-loops or multiple edges)
is_simple = not any(G_comp.has_edge(n, n) for n in G_comp.nodes())
print("Is complement a simple graph?", is_simple)

Q.2

import networkx as nx
import matplotlib.pyplot as plt

# (a) Complete Asymmetric Directed Graph on 10 vertices


DG = nx.DiGraph()
DG.add_nodes_from(range(1, 11))
for i in DG.nodes:
for j in DG.nodes:
if i != j:
DG.add_edge(i, j) # Directed edge from i to j

plt.figure(figsize=(6, 5))
nx.draw(DG, with_labels=True, node_color='violet',
edge_color='black', node_size=500, arrows=True)
plt.title("Asymmetric Directed Complete Graph (10 Vertices)")
plt.show()

# (b) Union of N7 and W12


N7 = nx.empty_graph(7)
W12 = nx.wheel_graph(12)
N7 = nx.relabel_nodes(N7, lambda x: f'N{x}')
W12 = nx.relabel_nodes(W12, lambda x: f'W{x}')

U = nx.union(N7, W12)
plt.figure(figsize=(8, 5))
nx.draw(U, with_labels=True, node_color='yellow', node_size=500,
edge_color='brown')
plt.title("Union of N7 and W12")
plt.show()

# (c) Vertex & Edge connectivity of K5 and K4,5


K5 = nx.complete_graph(5)
K45 = nx.complete_bipartite_graph(4, 5)

vk_K5 = nx.node_connectivity(K5)
ek_K5 = nx.edge_connectivity(K5)

vk_K45 = nx.node_connectivity(K45)
ek_K45 = nx.edge_connectivity(K45)

print("K5 - Vertex Connectivity:", vk_K5, ", Edge Connectivity:", ek_K5)


print("K4,5 - Vertex Connectivity:", vk_K45, ", Edge Connectivity:",
ek_K45)

Q.3

import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd

# --------- a) Directed Graph D1 ---------


D1 = nx.DiGraph()
D1.add_edges_from([(1,4), (2,3), (1,2), (5,3), (5,1), (4,1), (3,2), (5,2),
(5,4)])
# Plot D1
nx.draw(D1, with_labels=True, node_color='skyblue', node_size=600,
edge_color='black', arrows=True)
plt.title("Directed Graph D1")
plt.show()

# Underlying graph (ignore directions)


UG = D1.to_undirected()
nx.draw(UG, with_labels=True, node_color='orange', node_size=600)
plt.title("Underlying Graph of D1")
plt.show()

# In-degree and Out-degree


print("In-degree and Out-degree of D1:")
for v in D1.nodes():
print(f"Vertex {v}: In = {D1.in_degree(v)}, Out = {D1.out_degree(v)}")

# --------- b) Delete vertices & edges ---------


D1_modified = D1.copy()
D1_modified.remove_nodes_from([1,2])
D1_modified.remove_edges_from([(5,3)]) # (5,1) is already gone with
node 1

nx.draw(D1_modified, with_labels=True, node_color='lightgreen',


node_size=600, edge_color='red')
plt.title("D1 after removing vertices {1,2} and edge (5,3)")
plt.show()

# --------- c) Petersen Graph ---------


P = nx.petersen_graph()
nx.draw(P, with_labels=True, node_color='lightblue', node_size=600)
plt.title("Petersen Graph")
plt.show()

# Adjacency Matrix
adj_matrix = nx.to_numpy_array(P, dtype=int)
print("\nAdjacency Matrix of Petersen Graph:")
print(pd.DataFrame(adj_matrix))

# Incidence Matrix
edges = list(P.edges())
nodes = list(P.nodes())
inc_matrix = [[1 if v in e else 0 for e in edges] for v in nodes]

print("\nIncidence Matrix of Petersen Graph:")


print(pd.DataFrame(inc_matrix, index=nodes, columns=[f"e{i}" for i in
range(len(edges))]))
Slip 9 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) G1 = C5, G2 = K6
G1 = nx.cycle_graph(5)
G2 = nx.complete_graph(6)

# Intersection G3 = G1 ∩ G2
G3 = nx.intersection(G1, G2)

# Draw G3
nx.draw(G3, with_labels=True)
plt.title("Graph G3 = G1 ∩ G2")
plt.show()

# b) Bridges, Cut Vertices, Cut Sets in G3


print("Bridges:", list(nx.bridges(G3)))
print("Cut Vertices:", list(nx.articulation_points(G3)))

# Cut sets: All edges whose removal increases components


cut_sets = list(nx.all_edge_cuts(G3))
print("Cut Sets:", cut_sets)

# c) Eccentricity in G1
print("Eccentricity in G1:", nx.eccentricity(G1))
Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Connected Graph G
G = nx.Graph()
G.add_edges_from([(0,1),(1,2),(2,3),(3,0),(0,2)]) # A connected graph
nx.draw(G, with_labels=True)
plt.title("Graph G")
plt.show()

# Check if G is a tree
print("Is G a tree?", nx.is_tree(G))

# b) Spanning Tree of G
T = nx.minimum_spanning_tree(G)
nx.draw(T, with_labels=True)
plt.title("Spanning Tree of G")
plt.show()

# c) Regular Graph: 4 vertices, degree 2 (a 4-cycle)


R = nx.cycle_graph(4)
colors = ['red', 'green', 'blue', 'orange']
nx.draw(R, with_labels=True, node_color=colors)
plt.title("Regular Graph (4 vertices, degree 2)")
plt.show()
Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Graph G′
G = nx.DiGraph() # Use DiGraph to show (d,c) and (c,d) both
G.add_edges_from([('a','b'),('c','d'),('d','c'),('a','f'),
('g','h'),('e','e'),('a','h'),('d','h')])

# Draw G′ with red nodes, green edges


plt.figure()
nx.draw(G, with_labels=True, node_color='red', edge_color='green')
plt.title("Graph G′")
plt.show()

# b) Check connectivity
print("Is G′ connected (undirected)?",
nx.is_connected(G.to_undirected()))

# c) Draw C5, W6, K4, K4


plt.figure()
nx.draw(nx.cycle_graph(5), with_labels=True)
plt.title("C5 (Cycle Graph)")
plt.show()

plt.figure()
nx.draw(nx.wheel_graph(6), with_labels=True)
plt.title("W6 (Wheel Graph)")
plt.show()

plt.figure()
nx.draw(nx.complete_graph(4), with_labels=True)
plt.title("K4 (Complete Graph) - 1")
plt.show()

plt.figure()
nx.draw(nx.complete_graph(4), with_labels=True)
plt.title("K4 (Complete Graph) - 2")
plt.show()
Slip 10 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Directed Graph D2
D2 = nx.DiGraph()
D2.add_edges_from([(1,4), (2,3), (1,2), (1,3), (4,1), (3,2)])

# Draw D2
plt.figure()
nx.draw(D2, with_labels=True, node_color='lightblue',
edge_color='black', arrows=True)
plt.title("Directed Graph D2")
plt.show()

# Underlying Graph of D2 (undirected)


U = D2.to_undirected()
plt.figure()
nx.draw(U, with_labels=True, node_color='lightgreen')
plt.title("Underlying Graph of D2")
plt.show()

# In-degree and Out-degree


for v in D2.nodes():
print(f"Vertex {v} - In: {D2.in_degree(v)}, Out: {D2.out_degree(v)}")

# b) Connectivity and Components


is_conn = nx.is_connected(U)
components = nx.number_connected_components(U)
print("Is D2 connected (undirected)?", is_conn)
print("Number of components in D2 (undirected):", components)

# c) Petersen Graph and Handshaking Lemma


P = nx.petersen_graph()
plt.figure()
nx.draw(P, with_labels=True, node_color='pink')
plt.title("Petersen Graph")
plt.show()

# Handshaking Lemma: sum of degrees = 2 × edges


deg_sum = sum(dict(P.degree()).values())
edge_count = P.number_of_edges()
print("Sum of degrees:", deg_sum)
print("2 × number of edges:", 2 * edge_count)
print("Handshaking Lemma Verified?", deg_sum == 2 * edge_count)

Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Star graph (5 vertices)


S = nx.star_graph(4) # center + 4 leaves = 5 vertices
plt.figure()
nx.draw(S, with_labels=True, node_color='yellow')
plt.title("Star Graph (5 vertices)")
plt.show()
# Regular graph with 7 vertices, degree 6 (complete graph K7)
R = nx.complete_graph(7)
plt.figure()
nx.draw(R, with_labels=True, node_color='lightblue')
plt.title("7-vertex Regular Graph (Degree 6)")
plt.show()

# b) G1 = N5 (null graph), G2 = W6 (wheel graph)


G1 = nx.empty_graph(5)
G2 = nx.wheel_graph(6)

# Graph product (tensor product as default example)


G3 = nx.tensor_product(G1, G2)
plt.figure()
nx.draw(G3, with_labels=True, node_color='pink')
plt.title("Graph G3 = G1 × G2")
plt.show()

# c) Adjacency Matrix
A = nx.adjacency_matrix(G3).todense()
print("Adjacency Matrix of G3:\n", A)

# Incidence Matrix (using incidence_matrix from networkx)


I = nx.incidence_matrix(G3, oriented=False).todense()
print("Incidence Matrix of G3:\n", I)

Q.3

import networkx as nx
import matplotlib.pyplot as plt
# a) Simple Graph G with labels and colors
G = nx.Graph()
G.add_edges_from([('A','B'), ('A','C'), ('B','D'), ('C','D'), ('C','E')])

# Draw with custom colors


colors = ['red', 'green', 'blue', 'orange', 'purple']
plt.figure()
nx.draw(G, with_labels=True, node_color=colors, edge_color='gray')
plt.title("Simple Graph G")
plt.show()

# b) Center, Radius, Diameter


center = nx.center(G)
radius = nx.radius(G)
diameter = nx.diameter(G)
print("Center:", center)
print("Radius:", radius)
print("Diameter:", diameter)

# c) Balanced binary tree of height 2


T2 = nx.balanced_tree(r=2, h=2)
plt.figure()
nx.draw(T2, with_labels=True, node_color='lightblue')
plt.title("Balanced Binary Tree (Height 2)")
plt.show()

# Balanced binary tree of height 3


T3 = nx.balanced_tree(r=2, h=3)
plt.figure()
nx.draw(T3, with_labels=True, node_color='lightgreen')
plt.title("Balanced Binary Tree (Height 3)")
plt.show()
Slip 11 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Create Graph G
G = nx.Graph()
G.add_edges_from([(4,5), (5,3), (2,2), (2,3), (2,4), (3,4), (1,5)])

# Draw G with yellow nodes and blue edges


plt.figure()
nx.draw(G, with_labels=True, node_color='yellow', edge_color='blue')
plt.title("Graph G")
plt.show()

# b) Create a spanning tree T from G


T = nx.minimum_spanning_tree(G)

# Draw spanning tree


plt.figure()
nx.draw(T, with_labels=True, node_color='lightgreen',
edge_color='black')
plt.title("Spanning Tree T of G")
plt.show()

# c) Check if T is a binary tree


# Binary tree: max 2 children per node (i.e., node degree ≤ 3 in
undirected tree)
is_binary = all(T.degree(n) <= 3 for n in T.nodes())
print("Is T a binary tree?", is_binary)

Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) G1 and G2 with union G3


G1 = nx.path_graph(4) # Path: 0-1-2-3
G2 = nx.cycle_graph([4,5,6,7]) # Cycle: 4-5-6-7-4

G3 = nx.union(G1, G2, rename=('G1_', 'G2_'))

plt.figure()
nx.draw(G3, with_labels=True, node_color='lightblue')
plt.title("G3 = G1 ∪ G2")
plt.show()

# b) Complement of G3
Gc = nx.complement(G3)
plt.figure()
nx.draw(Gc, with_labels=True, node_color='lightpink')
plt.title("Complement of G3")
plt.show()

# c) Draw C7, W8, K6, K4,3, N4


graphs = [
(nx.cycle_graph(7), "C7 (Cycle)"),
(nx.wheel_graph(8), "W8 (Wheel)"),
(nx.complete_graph(6), "K6 (Complete)"),
(nx.complete_bipartite_graph(4, 3), "K4,3 (Complete Bipartite)"),
(nx.empty_graph(4), "N4 (Null)")
]

for g, title in graphs:


plt.figure()
nx.draw(g, with_labels=True, node_color='lightgreen')
plt.title(title)
plt.show()

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Symmetric directed graph on 7 vertices


DG = nx.DiGraph()
edges = [(0,1), (1,0), (2,3), (3,2), (4,5), (5,4), (6,0), (0,6)]
DG.add_edges_from(edges)

plt.figure()
nx.draw(DG, with_labels=True, node_size=700, node_color='red',
arrows=True)
plt.title("Symmetric Directed Graph (7 vertices)")
plt.show()

# b) Simple graph G′ with 6 vertices


G_prime = nx.Graph()
G_prime.add_edges_from([(0,1), (1,2), (2,3), (3,4), (4,5), (5,0)])

plt.figure()
nx.draw(G_prime, with_labels=True, node_color='skyblue')
plt.title("Simple Graph G′")
plt.show()

# Check if G′ is Eulerian
is_eulerian = nx.is_eulerian(G_prime)
print("Is G′ Eulerian?", is_eulerian)

# c) Adjacency and Incidence Matrix of G′


adj_matrix = nx.adjacency_matrix(G_prime).todense()
inc_matrix = nx.incidence_matrix(G_prime, oriented=False).todense()
print("Adjacency Matrix of G′:\n", adj_matrix)
print("Incidence Matrix of G′:\n", inc_matrix)
Slip 12 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Create graph G with labeled edges


G = nx.Graph()
edges = [('x','w'), ('x','y'), ('w','z'), ('y','z'), ('x','z')]
G.add_edges_from(edges)

labels = {'x':'x', 'w':'w', 'y':'y', 'z':'z'}


edge_labels = {('x','w'):'e1', ('x','y'):'e2', ('w','z'):'e3', ('y','z'):'e4',
('x','z'):'e5'}

plt.figure()
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_color='lightblue')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.title("Graph G with labeled vertices and edges")
plt.show()

# b) Hamiltonian check (brute force path search)


from itertools import permutations
def is_hamiltonian(graph):
nodes = list(graph.nodes)
for path in permutations(nodes):
if all(graph.has_edge(path[i], path[i+1]) for i in range(len(path)-1))
and graph.has_edge(path[-1], path[0]):
return True
return False

print("Is G Hamiltonian?", is_hamiltonian(G))

# c) Ternary tree of height 1 and 3


def draw_ternary_tree(height, title):
T = nx.balanced_tree(r=3, h=height)
plt.figure()
nx.draw(T, with_labels=True, node_color='lightgreen')
plt.title(f"Ternary Tree of Height {height}")
plt.show()

draw_ternary_tree(1, "Ternary Tree Height 1")


draw_ternary_tree(3, "Ternary Tree Height 3")

Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Create simple graph G′


G_prime = nx.Graph()
edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
G_prime.add_edges_from(edges)

# Draw graph G′
plt.figure()
nx.draw(G_prime, with_labels=True, node_color='lightblue',
edge_color='blue')
plt.title("Simple Graph G′")
plt.show()
# Find complement of G′ (Graph H)
H = nx.complement(G_prime)

# Draw complement graph H


plt.figure()
nx.draw(H, with_labels=True, node_color='lightgreen',
edge_color='orange')
plt.title("Complement Graph H")
plt.show()

# Check if H is a simple graph (no loops, no multiple edges)


is_simple = nx.is_simple_graph(H)
print("Is H a simple graph?", is_simple)

# b) Find three paths in G′


# Paths in G′:
paths = [
[0, 1, 2], # Path 1: 0 -> 1 -> 2
[2, 3, 4], # Path 2: 2 -> 3 -> 4
[4, 5, 6] # Path 3: 4 -> 5 -> 6
]
print("Paths in G′:", paths)

# c) Complete symmetric directed graph with 10 vertices


DG = nx.complete_graph(10, create_using=nx.DiGraph())

# Draw directed graph with custom colors


plt.figure()
nx.draw(DG, with_labels=True, node_color='purple',
edge_color='yellow', node_size=700, arrowsize=15)
plt.title("Complete Symmetric Directed Graph (10 vertices)")
plt.show()

Q.3

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# a) Draw Petersen graph and check regularity


G = nx.petersen_graph()
plt.figure()
nx.draw(G, with_labels=True, node_color='skyblue')
plt.title("Petersen Graph")
plt.show()

degrees = [d for n, d in G.degree()]


print("Is Petersen Graph 3-regular?", all(d == 3 for d in degrees))

# b) Draw K5 and complement of N5 (edgeless graph on 5


vertices)
K5 = nx.complete_graph(5)
N5 = nx.empty_graph(5)
H = nx.complement(N5)

plt.figure()
nx.draw(K5, with_labels=True, node_color='lightgreen')
plt.title("Complete Graph K5")
plt.show()

plt.figure()
nx.draw(H, with_labels=True, node_color='orange')
plt.title("Complement of N5")
plt.show()

# Check if K5 is isomorphic to H
print("Is K5 isomorphic to complement of N5?", nx.is_isomorphic(K5,
H))

# c) Adjacency & Incidence matrices of complement of Petersen


graph
G_comp = nx.complement(G)

# Adjacency matrix
A = nx.adjacency_matrix(G_comp).todense()
print("Adjacency Matrix of Complement of Petersen Graph:\n", A)

# Incidence matrix
def incidence_matrix(G):
nodes = list(G.nodes())
edges = list(G.edges())
mat = np.zeros((len(nodes), len(edges)), dtype=int)
for j, (u, v) in enumerate(edges):
i1, i2 = nodes.index(u), nodes.index(v)
mat[i1][j] = mat[i2][j] = 1
return mat

I = incidence_matrix(G_comp)
print("Incidence Matrix of Complement of Petersen Graph:\n", I)
Slip 13 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Complete graph G with 6 red vertices


G = nx.complete_graph(6)
plt.figure()
nx.draw(G, with_labels=True, node_color='red', node_size=700)
plt.title("Complete Graph G (6 vertices)")
plt.show()

# b) Verify Handshaking Lemma: sum of degrees = 2 * number of


edges
deg_sum = sum(dict(G.degree()).values())
edge_count = G.number_of_edges()
print("Handshaking Lemma Verified:", deg_sum == 2 * edge_count)

# c) Draw a connected graph and check if it’s Hamiltonian


H = nx.cycle_graph(5) # Cycle of 5 nodes (Hamiltonian)
plt.figure()
nx.draw(H, with_labels=True, node_color='lightblue')
plt.title("Connected Graph H")
plt.show()

# Check if Hamiltonian (simple cycle that visits every node once)


is_hamiltonian = nx.is_connected(H) and H.number_of_edges() >=
H.number_of_nodes()
print("Is Graph H Hamiltonian?", is_hamiltonian)
Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Check if G is bipartite
G = nx.Graph()
edges = [(1,2),(1,3),(4,3),(5,1),(4,5),(3,5)]
G.add_edges_from(edges)
print("Is G bipartite?", nx.is_bipartite(G))

# b) Petersen graph and check regularity


P = nx.petersen_graph()
plt.figure()
nx.draw(P, with_labels=True, node_color='lightgreen')
plt.title("Petersen Graph")
plt.show()

deg = [d for _, d in P.degree()]


print("Petersen Graph is 3-regular:", all(d == 3 for d in deg))

# c) Draw 4-ary tree of height 4 (each node has up to 4 children)


T = nx.balanced_tree(r=4, h=4)
plt.figure()
nx.draw(T, with_labels=True, node_size=300, node_color='orange')
plt.title("4-ary Tree of Height 4")
plt.show()

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Graph with 6 vertices and 6 edges


G = nx.Graph()
G.add_edges_from([(0,1), (1,2), (1,3), (3,4), (4,5), (2,5)])
print("Bridges:", list(nx.bridges(G)))
print("Cut Vertices:", list(nx.articulation_points(G)))

# b) Graph with 6 vertices and 10 edges, with labels


H = nx.Graph()
H.add_edges_from([(0,1), (0,2), (0,3), (0,4), (1,2), (1,3), (2,4), (3,5),
(4,5), (1,5)])
plt.figure()
nx.draw(H, with_labels=True, edge_color='blue',
node_color='skyblue')
nx.draw_networkx_edge_labels(H, pos=nx.spring_layout(H),
edge_labels={(u,v):f"{u}-{v}" for u,v in H.edges()})
plt.title("Graph with 6 vertices and 10 edges")
plt.show()

# c) Balanced binary tree of height 4 (2^5 - 1 = 31 nodes)


T = nx.balanced_tree(r=2, h=4)
plt.figure()
nx.draw(T, with_labels=True, node_color='lightgreen')
nx.draw_networkx_edge_labels(T, pos=nx.spring_layout(T))
plt.title("Balanced Binary Tree (Height 4)")
plt.show()
Slip 14 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# a) Regular graph on 4 vertices with degree 2 (a cycle)


G = nx.cycle_graph(4)
plt.figure()
nx.draw(G, with_labels=True, node_color='lightblue')
plt.title("Regular Graph (4 vertices, degree 2)")
plt.show()

Bridges, cut vertices, cut # b) sets


print("Bridges:", list(nx.bridges(G)))
print("Cut Vertices:", list(nx.articulation_points(G)))

# Cut sets (basic: remove one edge and check if graph


disconnected)
cut_sets = []
for e in G.edges():
G_temp = G.copy()
G_temp.remove_edge(*e)
if not nx.is_connected(G_temp):
cut_sets.append([e])
print("Cut Sets (minimal edge sets whose removal disconnects G):",
cut_sets)

# c) Adjacency and incidence matrix for Petersen Graph


P = nx.petersen_graph()
A = nx.adjacency_matrix(P).todense()
I = nx.incidence_matrix(P, oriented=False).todense()
print("Adjacency Matrix of Petersen Graph:\n", A)
print("Incidence Matrix of Petersen Graph:\n", I)

Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) K5 and complement of N5
K5 = nx.complete_graph(5)
N5 = nx.empty_graph(5)
H = nx.complement(N5)
print("K5 ≅ H ?", nx.is_isomorphic(K5, H))

plt.figure(figsize=(10,2))
plt.subplot(1,2,1)
nx.draw(K5, with_labels=True, node_color='lightblue')
plt.title("K5")
plt.subplot(1,2,2)
nx.draw(H, with_labels=True, node_color='lightgreen')
plt.title("Complement of N5 (H)")
plt.show()

# b) Symmetric directed graph on 6 vertices


D = nx.DiGraph()
edges = [(0,1),(1,0),(2,3),(3,2),(4,5),(5,4)]
D.add_edges_from(edges)
plt.figure()
nx.draw(D, with_labels=True, node_color='pink', arrows=True)
plt.title("Symmetric Directed Graph (6 vertices)")
plt.show()

# c) Draw C10, W3, K5


C10 = nx.cycle_graph(10)
W3 = nx.wheel_graph(4) # W3 means 3 outer + 1 center => 4 total
K5 = nx.complete_graph(5)

plt.figure(figsize=(15,3))
plt.subplot(1,3,1)
nx.draw(C10, with_labels=True, node_color='orange')
plt.title("C10")
plt.subplot(1,3,2)
nx.draw(W3, with_labels=True, node_color='violet')
plt.title("W3")
plt.subplot(1,3,3)
nx.draw(K5, with_labels=True, node_color='skyblue')
plt.title("K5")
plt.show()

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Union of G1 and G2
G1 = nx.Graph()
G1.add_edges_from([(1,2), (2,3), (3,4), (4,5)])
G2 = nx.Graph()
G2.add_edges_from([('a','b'), ('b','c'), ('c','d'), ('b','d')])
G3 = nx.disjoint_union(G1, G2)

plt.figure()
nx.draw(G3, with_labels=True, node_color='lightblue')
plt.title("Union of G1 and G2")
plt.show()

# b) Graph T with 8 vertices and 7 edges (a tree)


T = nx.Graph()
T.add_edges_from([(1,2),(1,3),(2,4),(2,5),(3,6),(3,7),(7,8)])
plt.figure()
nx.draw(T, with_labels=True, node_color='salmon')
plt.title("Graph T (8 vertices, 7 edges)")
plt.show()

# c) Check if T is binary tree (T must be a tree & every node ≤ 3


degree)
is_binary_tree = nx.is_tree(T) and all(T.degree(n) <= 3 for n in
T.nodes)
print("Is T a Binary Tree?:", is_binary_tree)
Slip 15 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Define G1
G1 = nx.Graph()
G1.add_edges_from([('a','b'), ('c','d'), ('a','e'), ('b','f'), ('a','f')])

# Check connectivity
print("Is G1 connected?:", nx.is_connected(G1))

# b) Complement of G1
Gc = nx.complement(G1)
plt.figure()
nx.draw(Gc, with_labels=True, node_color='lightgreen')
plt.title("Complement of G1")
plt.show()

# Is complement simple? (networkx creates simple graphs by


default)
is_simple = not any(Gc.has_edge(n, n) for n in Gc.nodes)
print("Is complement of G1 simple?:", is_simple)

# c) Info about G1
print("Number of vertices in G1:", G1.number_of_nodes())
print("Number of edges in G1:", G1.number_of_edges())
print("Degrees of all vertices in G1:")
for v, d in G1.degree():
print(f"Vertex {v}: Degree {d}")

Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Generate G1 and G2 and check isomorphism


G1 = nx.Graph()
G1.add_edges_from([(1,2), (2,3), (3,4), (4,1)])

G2 = nx.Graph()
G2.add_edges_from([('a','b'), ('b','c'), ('c','d'), ('d','a')])

print("G1 is isomorphic to G2?:", nx.is_isomorphic(G1, G2))

# b) Draw star graph G on 7 vertices


G = nx.star_graph(6) # center + 6 leaves = 7 vertices
plt.figure()
nx.draw(G, with_labels=True, node_color='orange', node_size=600)
plt.title("Star Graph with 7 Vertices")
plt.show()

# c) Verify Handshaking Lemma


degrees = [d for n, d in G.degree()]
sum_deg = sum(degrees)
print("Sum of degrees:", sum_deg)
print("Twice the number of edges:", 2 * G.number_of_edges())
print("Handshaking Lemma Verified?:", sum_deg == 2 *
G.number_of_edges())
Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Create G1 and check if connected


G1 = nx.Graph()
G1.add_edges_from([('a','b'), ('c','d'), ('a','e'), ('b','f'), ('a','f')])
print("G1 is connected?:", nx.is_connected(G1))

# b) Draw complement of G1 and check if simple


G1_comp = nx.complement(G1)
plt.figure()
nx.draw(G1_comp, with_labels=True, node_color='lightblue')
plt.title("Complement of G1")
plt.show()
print("Complement is simple graph?:", nx.is_simple_path(G1_comp,
list(G1_comp.nodes())) == False)

# c) Graph info
print("Vertices in G1:", list(G1.nodes()))
print("Number of vertices:", G1.number_of_nodes())
print("Number of edges:", G1.number_of_edges())
print("Degrees of all vertices:")
for node, degree in G1.degree():
print(f"{node}: {degree}")
Slip 16 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Create a graph T with 7 vertices and 10 edges


T = nx.Graph()
edges = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (1, 4), (2, 5), (3, 6),
(4, 7)]
T.add_edges_from(edges)

# Draw the graph T with labeled vertices and a chosen color


plt.figure()
nx.draw(T, with_labels=True, node_color='lightgreen', node_size=700,
font_weight='bold')
plt.title("Graph T with 7 vertices and 10 edges")
plt.show()

# b) Check if T is a binary tree (A binary tree has exactly 1 root


and each node has 0, 1, or 2 children)
is_binary_tree = nx.is_tree(T) and all(d <= 2 for _, d in T.degree())
print("Is T a binary tree?:", is_binary_tree)

# c) Find the center, radius, and diameter of the tree


if nx.is_tree(T):
center = nx.center(T)
radius = nx.radius(T)
diameter = nx.diameter(T)
print("Center of T:", center)
print("Radius of T:", radius)
print("Diameter of T:", diameter)
else:
print("T is not a tree, so cannot compute center, radius, and
diameter.")

Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Generate graph G with given vertices and edges


G = nx.Graph()
edges_G = [('a', 'b'), ('c', 'd'), ('a', 'c'), ('c', 'e')]
G.add_edges_from(edges_G)

# Draw graph G with red vertices and green edges


plt.figure()
nx.draw(G, with_labels=True, node_color='red', edge_color='green',
node_size=700, font_weight='bold')
plt.title("Graph G with vertices in red and edges in green")
plt.show()

# b) Add vertex f and edges (b,f) and (c,f)


G.add_node('f')
G.add_edges_from([('b', 'f'), ('c', 'f')])

# Check if the new graph G1 is connected


is_connected = nx.is_connected(G)
print("Is the new graph G1 connected?", is_connected)
# c) Find all paths from vertex a to d in the updated graph G1
paths = list(nx.all_simple_paths(G, source='a', target='d'))
print("All paths from a to d:", paths)

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Regular graph on 5 vertices with degree 4


G1 = nx.Graph()
G1.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 5), (5, 1), (1, 3), (2, 4), (3,
5), (4, 1), (5, 2)])
nx.draw(G1, with_labels=True, node_color='lightblue',
edge_color='green', node_size=700)
plt.title("Regular Graph on 5 vertices")
plt.show()

# b) Draw Petersen graph and check its regularity


G2 = nx.petersen_graph()
nx.draw(G2, with_labels=True, node_color='orange',
edge_color='purple', node_size=700)
plt.title("Petersen Graph")
plt.show()
print("Petersen Graph is", "3-regular" if all(d == 3 for _, d in
G2.degree()) else "Not 3-regular")

# c) Handshaking Lemma for Petersen graph


print("Handshaking Lemma:", sum(dict(G2.degree()).values()) // 2)
Slip 17 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# a) Create simple graph G1 and find adjacency and incidence


matrices
G1 = nx.Graph()
G1.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1)]) # Example simple
graph

# Adjacency Matrix
adj_matrix = nx.adjacency_matrix(G1).todense()
print("Adjacency Matrix of G1:")
print(adj_matrix)

# Incidence Matrix
inc_matrix = nx.incidence_matrix(G1).todense()
print("Incidence Matrix of G1:")
print(inc_matrix)

# b) Find union of G2 = K5 and G3 = N7


G2 = nx.complete_graph(5) # K5
G3 = nx.null_graph() # N7 (Empty graph with 7 vertices)
G3.add_nodes_from(range(7))

# Union of G2 and G3
G_union = nx.compose(G2, G3)
# Draw the union graph
plt.figure()
nx.draw(G_union, with_labels=True, node_color='lightblue',
edge_color='green', node_size=700)
plt.title("Union of G2 (K5) and G3 (N7)")
plt.show()

# c) Draw Wheel Graphs W12 and W20


W12 = nx.wheel_graph(12)
W20 = nx.wheel_graph(20)

# Draw W12
plt.figure()
nx.draw(W12, with_labels=True, node_color='lightblue',
edge_color='purple', node_size=700)
plt.title("Wheel Graph W12")
plt.show()

# Draw W20
plt.figure()
nx.draw(W20, with_labels=True, node_color='lightgreen',
edge_color='orange', node_size=700)
plt.title("Wheel Graph W20")
plt.show()

Q.2

import networkx as nx
import matplotlib.pyplot as plt
# a) Generate graph G with vertex set {1,2,3,4,5} and specified
edge set
G = nx.Graph()
G.add_edges_from([(4, 5), (5, 3), (2, 1), (2, 3), (2, 4), (3, 4), (1, 5)])

# Draw the graph G with vertices in red and edges in green


plt.figure()
nx.draw(G, with_labels=True, node_color='red', edge_color='green',
node_size=700)
plt.title("Graph G with Vertices in Red and Edges in Green")
plt.show()

# b) Verify Handshaking lemma for the above graph G


# Handshaking Lemma: Sum of all vertex degrees is twice the
number of edges
degree_sum = sum(dict(G.degree()).values())
num_edges = G.number_of_edges()
print("Handshaking Lemma Verification:")
print(f"Sum of degrees: {degree_sum}, Number of edges:
{num_edges}")
print(f"Handshaking Lemma holds: {degree_sum == 2 * num_edges}")

# c) Draw balanced binary trees of heights 2, 4, and 5

# Height 2
tree_2 = nx.balanced_tree(r=2, h=2)
plt.figure()
nx.draw(tree_2, with_labels=True, node_color='lightblue',
edge_color='brown', node_size=700)
plt.title("Balanced Binary Tree of Height 2")
plt.show()
# Height 4
tree_4 = nx.balanced_tree(r=2, h=4)
plt.figure()
nx.draw(tree_4, with_labels=True, node_color='lightgreen',
edge_color='brown', node_size=700)
plt.title("Balanced Binary Tree of Height 4")
plt.show()

# Height 5
tree_5 = nx.balanced_tree(r=2, h=5)
plt.figure()
nx.draw(tree_5, with_labels=True, node_color='lightcoral',
edge_color='brown', node_size=700)
plt.title("Balanced Binary Tree of Height 5")
plt.show()

Q.3

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# a) Generate graph G with specified vertex set and edge set


G = nx.Graph()
G.add_edges_from([('v', 'w'), ('x', 'y'), ('w', 'z'), ('v', 'z'), ('x', 'z')])

# Draw the graph G with labeled vertices and edges


plt.figure(figsize=(6, 6))
nx.draw(G, with_labels=True, node_color='lightblue',
edge_color='green', node_size=700, font_size=15)
plt.title("Graph G with Labeled Vertices and Edges")
plt.show()

# b) Find adjacency matrix


adj_matrix = nx.adjacency_matrix(G).todense()
print("Adjacency Matrix:")
print(adj_matrix)

# Find incidence matrix


inc_matrix = nx.incidence_matrix(G).todense()
print("\nIncidence Matrix:")
print(inc_matrix)

# c) Find the number of vertices, number of edges, and degree of


all vertices
num_vertices = G.number_of_nodes()
num_edges = G.number_of_edges()
degrees = dict(G.degree())

print(f"\nNumber of vertices: {num_vertices}")


print(f"Number of edges: {num_edges}")
print("Degree of each vertex:", degrees)
Slip 18 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) graph 𝐺1 = C6 and G2 = 𝐾3.


# G1 = C6
G1 = nx.cycle_graph(6)
G1 = nx.relabel_nodes(G1, {i: i+1 for i in range(6)})

# G2 = K3
G2 = nx.complete_graph([1, 2, 3])

# G3 = Intersection of G1 and G2
G3 = nx.intersection(G1, G2)

# Draw G3
plt.figure(figsize=(4, 4))
nx.draw(G3, with_labels=True, node_color='lightblue',
edge_color='green', node_size=700)
plt.title("G3 = Intersection of G1 (C6) and G2 (K3)")
plt.show()

# b) Find Bridges, Cut Vertices and Cut Sets in G3


bridges = list(nx.bridges(G3))
cut_vertices = list(nx.articulation_points(G3))

print("Bridges in G3:", bridges)


print("Cut Vertices in G3:", cut_vertices)
# Cut sets = edges whose removal increases components
cut_sets = bridges # in simple graphs, bridge edges form minimal cut
sets
print("Cut Sets (edges):", cut_sets)

# c) Eccentricity of vertices in G1 and G2


ecc_G1 = nx.eccentricity(G1)
ecc_G2 = nx.eccentricity(G2)

print("\nEccentricities in G1 (C6):", ecc_G1)


print("Eccentricities in G2 (K3):", ecc_G2)

Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Draw star graph G on 7 vertices


G = nx.star_graph(6) # center node 0, connected to 1 through 6

# Draw the star graph


plt.figure(figsize=(5, 5))
nx.draw(
G,
with_labels=True,
node_color='orange',
node_size=600,
edge_color='black'
)
plt.title("Star Graph G with 7 Vertices")
plt.show()

# b) Verify Handshaking Lemma


# Sum of degrees = 2 * number of edges
degree_sum = sum(dict(G.degree()).values())
num_edges = G.number_of_edges()
handshaking_valid = degree_sum == 2 * num_edges

# c) Draw complement of G and check if it is simple


G_complement = nx.complement(G)

# Draw the complement graph


plt.figure(figsize=(5, 5))
nx.draw(
G_complement,
with_labels=True,
node_color='lightblue',
node_size=600,
edge_color='red'
)
plt.title("Complement of Star Graph G")
plt.show()

# Check if complement is simple


is_simple = nx.is_simple_path(G_complement) or True # All
NetworkX graphs are simple by default unless otherwise

# Return values for display


degree_sum, num_edges, handshaking_valid,
G_complement.number_of_edges(), is_simple
Q.3
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# a) Create graph G
G = nx.Graph()
G.add_nodes_from([1, 2, 3, 4, 5])
G.add_edges_from([(4, 5), (5, 3), (2, 2), (2, 3), (2, 4), (3, 4), (1, 5)]) #
Includes self-loop (2,2)

# Draw graph
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_color='blue',
edge_color='red', node_size=700, font_color='white')
plt.title("Graph G")
plt.show()

# b) Adjacency matrix
adj_matrix = nx.adjacency_matrix(G).todense()
print("Adjacency Matrix:\n", adj_matrix)

# Incidence matrix (manually done for clarity)


inc_matrix = nx.incidence_matrix(G, oriented=False).todense()
print("Incidence Matrix:\n", inc_matrix)

# c) Graph info
print("Number of vertices:", G.number_of_nodes())
print("Number of edges:", G.number_of_edges())
print("Degree of each vertex:")
for node in G.nodes():
print(f"Vertex {node}: Degree {G.degree(node)}")
Slip 19 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Create G′
G_prime = nx.DiGraph() # Use DiGraph to allow both (c,d) and (d,c)
G_prime.add_nodes_from(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
G_prime.add_edges_from([('a', 'b'), ('c', 'd'), ('d', 'c'),
('a', 'f'), ('g', 'h'), ('e', 'e'),
('a', 'h'), ('d', 'h')])

# Draw G′ with red nodes and green edges


plt.figure(figsize=(5,4))
nx.draw(G_prime, with_labels=True, node_color='red',
edge_color='green', node_size=700, font_color='white')
plt.title("Graph G′")
plt.show()

# b) Check if G′ is connected
# Convert to undirected for connected check
if nx.is_connected(G_prime.to_undirected()):
print("G′ is a connected graph.")
else:
print("G′ is NOT a connected graph.")

# c) Draw C5, W6, K4, K4


# C5
C5 = nx.cycle_graph(5)
plt.figure(figsize=(4,3))
nx.draw(C5, with_labels=True, node_color='skyblue',
edge_color='black')
plt.title("Cycle Graph C5")
plt.show()

# W6
W6 = nx.wheel_graph(6)
plt.figure(figsize=(4,3))
nx.draw(W6, with_labels=True, node_color='orange',
edge_color='black')
plt.title("Wheel Graph W6")
plt.show()

# K4 (draw twice)
K4_1 = nx.complete_graph(4)
plt.figure(figsize=(4,3))
nx.draw(K4_1, with_labels=True, node_color='lightgreen',
edge_color='black')
plt.title("Complete Graph K4 (1st)")
plt.show()

K4_2 = nx.complete_graph(4)
plt.figure(figsize=(4,3))
nx.draw(K4_2, with_labels=True, node_color='lightcoral',
edge_color='black')
plt.title("Complete Graph K4 (2nd)")
plt.show()
Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Simple Graph G1
G1 = nx.Graph()
G1.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1)]) # Just a square

# Adjacency Matrix of G1
adj_G1 = nx.adjacency_matrix(G1).todense()
print("Adjacency Matrix of G1:\n", adj_G1)

# Incidence Matrix of G1
inc_G1 = nx.incidence_matrix(G1, oriented=False).todense()
print("Incidence Matrix of G1:\n", inc_G1)

# Drawing G1
plt.figure()
nx.draw(G1, with_labels=True, node_color='violet',
edge_color='black')
plt.title("Simple Graph G1")
plt.show()

# b) G2 = K4 (Complete), G3 = N4 (Null Graph), Intersection


G2 = nx.complete_graph(4)
G3 = nx.empty_graph(4)

# Intersection
G_inter = nx.intersection(G2, G3)
plt.figure()
nx.draw(G_inter, with_labels=True, node_color='lightgrey',
edge_color='black')
plt.title("Intersection of K4 and N4 (G2 ∩ G3)")
plt.show()

# c) Draw W21 and W30


W21 = nx.wheel_graph(21)
plt.figure()
nx.draw(W21, with_labels=False, node_color='cyan',
edge_color='black', node_size=100)
plt.title("Wheel Graph W21")
plt.show()

W30 = nx.wheel_graph(30)
plt.figure()
nx.draw(W30, with_labels=False, node_color='pink',
edge_color='black', node_size=80)
plt.title("Wheel Graph W30")
plt.show()

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Null Graph on 12 vertices


nx.draw(nx.empty_graph(12), with_labels=True, node_color='red',
node_size=600)
plt.title("Null Graph (12)")
plt.show()
# b) Asymmetric Directed Graph (10 vertices)
DG = nx.DiGraph([(0,1),(1,3),(2,5),(5,6),(6,7),(7,9),(3,8),(4,2)])
nx.draw(DG, with_labels=True, node_color='skyblue', node_size=700,
arrows=True)
plt.title("Asymmetric Directed Graph (10)")
plt.show()

# c) Ternary Trees of Height 1 and 3


for h in [1, 3]:
T = nx.balanced_tree(r=3, h=h)
nx.draw(T, with_labels=True, node_color='lightgreen',
node_size=600)
plt.title(f"Ternary Tree Height {h}")
plt.show()
Slip 20 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Original Graph G
G = nx.Graph()
G.add_edges_from([('a','b'), ('c','d'), ('a','c'), ('c','e')])
nx.draw(G, with_labels=True, node_color='red', edge_color='green',
node_size=700); plt.title("Graph G"); plt.show()

# b) Add vertex f and edges → G1


G.add_edges_from([('b','f'), ('c','f')])
nx.draw(G, with_labels=True, node_color='red', edge_color='green',
node_size=700); plt.title("Graph G1"); plt.show()
print("Connected:" , nx.is_connected(G))

# c) All paths from 'a' to 'd'


paths = list(nx.all_simple_paths(G, source='a', target='d'))
for i, path in enumerate(paths, 1): print(f"Path {i}:", ' → '.join(path))

Q.2

import networkx as nx
Import matplotlib.pyplot as plt

# a) Connected Graph G
G = nx.Graph([(1,2), (2,3), (3,4), (4,1)])
nx.draw(G, with_labels=True, node_color='orange', edge_color='blue',
node_size=700)
plt.title("Connected Graph G")
plt.show()
print("Is G a tree?:", nx.is_tree(G))

# b) Spanning Tree of G
T = nx.minimum_spanning_tree(G)
nx.draw(T, with_labels=True, node_color='orange',
edge_color='green', node_size=700)
plt.title("Spanning Tree of G")
plt.show()

# c) Regular Graph on 4 vertices (Degree 2)


R = nx.cycle_graph(4)
nx.draw(R, with_labels=True, node_color='purple', edge_color='pink',
node_size=700)
plt.title("Regular Graph (Degree 2)")
plt.show()

Q.3

import networkx as nx, matplotlib.pyplot as plt

# a) Regular Graph on 6 vertices with degree 3


G = nx.random_regular_graph(d=3, n=6)
nx.draw(G, with_labels=True, node_color='skyblue',
edge_color='black', node_size=700)
edge_labels = nx.convert_matrix.to_dict_of_dicts(G)
nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G),
edge_labels={(u,v):f"{u}-{v}" for u,v in G.edges()})
plt.title("3-Regular Graph (6 Vertices)")
plt.show()

# b) Petersen Graph and check regularity


P = nx.petersen_graph()
nx.draw(P, with_labels=True, node_color='lightcoral',
edge_color='black', node_size=700)
plt.title("Petersen Graph")
plt.show()

degrees = [d for n, d in P.degree()]


is_3_regular = all(d == 3 for d in degrees)
print("Petersen Graph is 3-regular:" , is_3_regular)

# c) Handshaking Lemma → sum of degrees = 2 * number of


edges
deg_sum = sum(degrees)
edge_count = P.number_of_edges()
print("Sum of degrees:", deg_sum)
print("2 × Number of edges:", 2 * edge_count)
print("Handshaking Lemma Verified:", deg_sum == 2 * edge_count)
Slip 21 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Tree T with 8 vertices and 7 edges


T = nx.Graph()
T.add_edges_from([(1,2), (1,3), (2,4), (2,5), (3,6), (3,7), (7,8)])
nx.draw(T, with_labels=True, node_color='lightgreen',
edge_color='black', node_size=700)
plt.title("Graph T with 8 Vertices & 7 Edges")
plt.show()

# b) Check if T is a binary tree


is_tree = nx.is_tree(T)
max_deg = max(dict(T.degree()).values())
print("Is T a tree?:", is_tree)
print("Max degree in T:", max_deg)
print("Is T a binary tree?:", is_tree and max_deg <= 3)

# c) Center, Radius, Diameter


center = nx.center(T)
radius = nx.radius(T)
diameter = nx.diameter(T)
print("Center:", center)
print("Radius:", radius)
print("Diameter:", diameter)
Q.2

import networkx as nx
Import matplotlib.pyplot as plt

# a) Simple graph G′
G = nx.Graph([(1,2), (2,3), (3,4), (4,5)])
nx.draw(G, with_labels=True, node_color='orange',
edge_color='black', node_size=700)
plt.title("Graph G′")
plt.show()
# Complement graph H
H = nx.complement(G)
nx.draw(H, with_labels=True, node_color='skyblue',
edge_color='green', node_size=700)
plt.title("Complement Graph H")
plt.show()

print("Is H simple?:", nx.is_simple_path(H.edges))

# b) Any 3 paths in G′
paths = list(nx.all_simple_paths(G, source=1, target=5))
for i, path in enumerate(paths[:3], 1): print(f"Path {i}:", ' →
'.join(map(str, path)))

# c) Complete symmetric directed graph (10 vertices)


DG = nx.complete_graph(10, create_using=nx.DiGraph())
DG.add_edges_from([(j,i) for i,j in DG.edges()]) # Make symmetric
nx.draw(DG, with_labels=True, node_color='lightpink',
edge_color='purple', node_size=600, arrows=True)
plt.title("Complete Symmetric Directed Graph (10 Vertices)")
plt.show()
Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Two graphs G1 and G2, then union → G3


G1 = nx.Graph([(1,2), (2,3)])
G2 = nx.Graph([(4,5), (5,6)])
G3 = nx.union(G1, G2, rename=('G1-', 'G2-'))

nx.draw(G3, with_labels=True, node_color='lightblue',


edge_color='black', node_size=700)
plt.title("G3: Union of G1 and G2")
plt.show()

# b) Complement of G3
H = nx.complement(G3)
nx.draw(H, with_labels=True, node_color='lightgreen',
edge_color='red', node_size=700)
plt.title("Complement of G3")
plt.show()

# c) Draw graphs: C7, W8, K6, K4,3


graphs = {
"Cycle Graph C7": nx.cycle_graph(7),
"Wheel Graph W8": nx.wheel_graph(8),
"Complete Graph K6": nx.complete_graph(6),
"Complete Bipartite Graph K4,3": nx.complete_bipartite_graph(4, 3)
}

for title, graph in graphs.items():


nx.draw(graph, with_labels=True, node_color='violet',
edge_color='black', node_size=700)
plt.title(title)
plt.show()
Slip 22 ❗️
Q.1

import networkx as nx
Import matplotlib.pyplot as plt

# a) Complete Bipartite Graphs K4,3 and K5,9


B1 = nx.complete_bipartite_graph(4, 3)
nx.draw(B1, with_labels=True, node_color='lightblue',
edge_color='black', node_size=700)
plt.title("Complete Bipartite Graph K4,3")
plt.show()

B2 = nx.complete_bipartite_graph(5, 9)
nx.draw(B2, with_labels=True, node_color='lightgreen',
edge_color='black', node_size=500)
plt.title("Complete Bipartite Graph K5,9")
plt.show()

# b) Any Connected Graph G & check if it's a tree


G = nx.Graph([(1,2), (2,3), (3,4), (4,5)])
nx.draw(G, with_labels=True, node_color='orange', edge_color='blue',
node_size=700)
plt.title("Connected Graph G")
plt.show()
print("Is G a tree?:", nx.is_tree(G))

# c) Graph G = {(p,q), (q,r), (r,s), (p,s)} and check if Eulerian


G2 = nx.Graph([('p','q'), ('q','r'), ('r','s'), ('p','s')])
nx.draw(G2, with_labels=True, node_color='pink', edge_color='purple',
node_size=700)
plt.title("Graph G = {(p,q), (q,r), (r,s), (p,s)}")
plt.show()
print("Is G Eulerian?:", nx.is_eulerian(G2))

Q.2

import networkx as nx
Import matplotlib.pyplot as plt

# a) Graph G′ with given vertices and edges


G = nx.Graph([(1,5), (1,3), (2,3), (2,4), (3,4), (4,5)])
nx.draw(G, with_labels=True, node_color='lightcoral',
edge_color='black', node_size=700)
plt.title("Graph G′")
plt.show()

# b) Degree of all vertices & check if connected


print("Degrees:")
for node, deg in G.degree(): print(f"Vertex {node}: Degree {deg}")
print("Is G′ connected?:", nx.is_connected(G))

# c) Cycle graph C12 with blue vertices


C = nx.cycle_graph(12)
nx.draw(C, with_labels=True, node_color='blue', edge_color='black',
node_size=600, font_color='white')
plt.title("Cycle Graph C12")
plt.show()
Q.3

import networkx as nx
Import matplotlib.pyplot as plt
import numpy as np

# a) Define G1 and G2
G1 = nx.Graph([(1,2), (2,3), (3,4), (4,5), (1,4)])
G2 = nx.Graph([('a','b'), ('b','c'), ('c','d'), ('b','d'), ('a','c')])

# To find intersection, relabel G2 to match G1-style labels


mapping = {'a':1, 'b':2, 'c':3, 'd':4}
G2_relabeled = nx.relabel_nodes(G2, mapping, copy=True)
G_intersection = nx.intersection(G1, G2_relabeled)

nx.draw(G_intersection, with_labels=True, node_color='lightblue',


edge_color='green', node_size=700)
plt.title("Intersection of G1 and G2")
plt.show()

# b) Eccentricity of G1
ecc = nx.eccentricity(G1)
print("Eccentricity of each vertex in G1:")
for v, e in ecc.items(): print(f"Vertex {v}: {e}")

# c) Adjacency and Incidence Matrix of G2


print("\nAdjacency Matrix of G2:")
A = nx.adjacency_matrix(G2).todense()
print(A)

print("\nIncidence Matrix of G2:")


nodes = list(G2.nodes())
edges = list(G2.edges())
I = np.zeros((len(nodes), len(edges)), dtype=int)
for j, (u,v) in enumerate(edges):
I[nodes.index(u)][j] = 1
I[nodes.index(v)][j] = 1
print(I)
Slip 23 ❗️
Q.1

import networkx as nx
Import matplotlib.pyplot as plt

# a) Graph G with given vertices and edges


G = nx.Graph([(1,5), (1,3), (2,3), (2,4), (3,4), (4,5)])
nx.draw(G, with_labels=True, node_color='lightblue',
edge_color='black', node_size=700)
plt.title("Graph G")
plt.show()

# b) Degree of all vertices & check if connected


print("Degrees of vertices:")
for node, deg in G.degree():
print(f"Vertex {node}: Degree {deg}")
print("Is G connected?:", nx.is_connected(G))

# c) Cycle graph C31 with blue vertices and node size 100
C31 = nx.cycle_graph(31)
nx.draw(C31, with_labels=True, node_color='blue',
edge_color='black', node_size=100, font_color='white')
plt.title("Cycle Graph C31")
plt.show()
Q.2

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# a) Define G1 and G2
G1 = nx.Graph([(1,2), (2,3), (3,4), (4,5), (1,4)])
G2 = nx.Graph([('a','b'), ('b','c'), ('c','d'), ('b','d'), ('a','c')])

# Union of G1 and G2 (relabel G2 for consistency)


mapping = {'a':1, 'b':2, 'c':3, 'd':4}
G2_relabeled = nx.relabel_nodes(G2, mapping, copy=True)
G_union = nx.union(G1, G2_relabeled)

nx.draw(G_union, with_labels=True, node_color='lightgreen',


edge_color='black', node_size=700)
plt.title("Union of Graph G1 and G2")
plt.show()

# b) Eccentricity of vertices in G2
ecc_G2 = nx.eccentricity(G2_relabeled)
print("\nEccentricity of each vertex in G2:")
for v, e in ecc_G2.items():
print(f"Vertex {v}: Eccentricity {e}")

# c) Adjacency and Incidence Matrix of G1


print("\nAdjacency Matrix of G1:")
A_G1 = nx.adjacency_matrix(G1).todense()
print(A_G1)

print("\nIncidence Matrix of G1:")


nodes_G1 = list(G1.nodes())
edges_G1 = list(G1.edges())
I_G1 = np.zeros((len(nodes_G1), len(edges_G1)), dtype=int)
for j, (u, v) in enumerate(edges_G1):
I_G1[nodes_G1.index(u), j] = 1
I_G1[nodes_G1.index(v), j] = 1
print(I_G1)

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Complete Bipartite Graphs K5,3 and K5,9


B1 = nx.complete_bipartite_graph(5, 3)
nx.draw(B1, with_labels=True, node_color='lightblue',
edge_color='black', node_size=700)
plt.title("Complete Bipartite Graph K5,3")
plt.show()

B2 = nx.complete_bipartite_graph(5, 9)
nx.draw(B2, with_labels=True, node_color='lightgreen',
edge_color='black', node_size=500)
plt.title("Complete Bipartite Graph K5,9")
plt.show()

# b) Any Connected Graph G & check if it's a tree


G = nx.Graph([(1,2), (2,3), (3,4), (4,5)])
nx.draw(G, with_labels=True, node_color='orange', edge_color='blue',
node_size=700)
plt.title("Connected Graph G")
plt.show()
print("Is G a tree?:", nx.is_tree(G))

# c) Graph G = {(p,q), (q,r), (r,s), (p,s)} and check if Hamiltonian


G2 = nx.Graph([('p','q'), ('q','r'), ('r','s'), ('p','s')])
nx.draw(G2, with_labels=True, node_color='pink', edge_color='purple',
node_size=700)
plt.title("Graph G = {(p,q), (q,r), (r,s), (p,s)}")
plt.show()
print("Is G Hamiltonian?:", nx.is_hamiltonian(G2))
Slip 24 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Asymmetric Directed Graph on 10 vertices


D1 = nx.DiGraph()
D1.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 5), (6, 7), (7, 8), (8, 9), (9,
10), (1, 6), (5, 9)])
nx.draw(D1, with_labels=True, node_color='lightblue',
edge_color='black', node_size=700, arrowsize=15)
plt.title("Asymmetric Directed Graph on 10 vertices")
plt.show()

# b) Complete Bipartite Graphs K2,2, K8,6, K2,6


B1 = nx.complete_bipartite_graph(2, 2)
B2 = nx.complete_bipartite_graph(8, 6)
B3 = nx.complete_bipartite_graph(2, 6)

# K2,2
nx.draw(B1, with_labels=True, node_color='lightgreen',
edge_color='black', node_size=700)
plt.title("Complete Bipartite Graph K2,2")
plt.show()

# K8,6
nx.draw(B2, with_labels=True, node_color='lightcoral',
edge_color='black', node_size=700)
plt.title("Complete Bipartite Graph K8,6")
plt.show()

# K2,6
nx.draw(B3, with_labels=True, node_color='lightyellow',
edge_color='black', node_size=700)
plt.title("Complete Bipartite Graph K2,6")
plt.show()

# c) Intersection of K2,2 and K3


K2_2 = nx.complete_bipartite_graph(2, 2)
K3 = nx.complete_graph(3)

# Find intersection
K_intersection = nx.intersection(K2_2, K3)

nx.draw(K_intersection, with_labels=True, node_color='lightblue',


edge_color='black', node_size=700)
plt.title("Intersection of K2,2 and K3")
plt.show()

Q.2

import networkx as nx, matplotlib.pyplot as plt

# a) Create simple graph G1 with nodes and edges in custom


colors
G1 = nx.Graph([(1, 2), (2, 3), (3, 4), (1, 4), (2, 4)])

# Custom colors
nx.draw(G1, with_labels=True, node_color='skyblue',
edge_color='orange', node_size=800, font_size=12)
plt.title("Graph G1")
plt.show()

# b) Check if G1 is connected
print("Is G1 connected?:", nx.is_connected(G1))

# c) Draw complement of G1 and check if it is simple


G1_complement = nx.complement(G1)
nx.draw(G1_complement, with_labels=True, node_color='lightgreen',
edge_color='purple', node_size=800, font_size=12)
plt.title("Complement of Graph G1")
plt.show()

# Check if complement is a simple graph


print("Is the complement of G1 a simple graph?:",
nx.is_simple_path(G1_complement))

Q.3

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# a) Generate graph G with given vertex set and edge set


G = nx.Graph()
edges = [(4, 7), (5, 3), (2, 2), (2, 3), (2, 4), (3, 4), (1, 5), (3, 6), (6, 7)]
G.add_edges_from(edges)

# Draw graph with blue vertices and red edges


nx.draw(G, with_labels=True, node_color='blue', edge_color='red',
node_size=800, font_size=12)
plt.title("Graph G")
plt.show()

# b) Find adjacency matrix for the graph G


adj_matrix = nx.adjacency_matrix(G).todense()
print("Adjacency Matrix:")
print(np.array(adj_matrix))

# Find incidence matrix for the graph G


inc_matrix = nx.incidence_matrix(G).todense()
print("\nIncidence Matrix:")
print(np.array(inc_matrix))

# c) Find number of vertices, edges and degree of all vertices


num_vertices = G.number_of_nodes()
num_edges = G.number_of_edges()
degrees = dict(G.degree())

print("\nNumber of vertices:", num_vertices)


print("Number of edges:", num_edges)
print("Degree of all vertices:", degrees)
Slip 25 ❗️
Q.1

import networkx as nx
import matplotlib.pyplot as plt

# a) Create graph T with 8 vertices and 9 edges


T = nx.Graph()
edges = [(1, 2), (1, 3), (2, 4), (3, 5), (3, 6), (4, 7), (5, 7), (6, 8), (7, 8)]
T.add_edges_from(edges)

# Draw graph with labeled vertices and custom colors


nx.draw(T, with_labels=True, node_color='skyblue',
edge_color='green', node_size=800, font_size=12)
plt.title("Graph T with 8 vertices and 9 edges")
plt.show()

# b) Check if T is a binary tree (a binary tree must be connected


and have exactly n-1 edges)
is_binary_tree = nx.is_connected(T) and len(T.edges) == len(T.nodes)
-1
print("Is T a binary tree?:", is_binary_tree)

# c) Find center, radius, and diameter of the tree T


center = nx.center(T)
radius = nx.radius(T)
diameter = nx.diameter(T)
print("\nCenter of T:", center)
print("Radius of T:", radius)
print("Diameter of T:", diameter)
Q.2

import networkx as nx
import matplotlib.pyplot as plt

# a) Generate graph G with vertex set {a, b, c, d, e} and edge set


{(a, b), (c, d), (a, c), (c, e)}
G = nx.Graph()
edges = [('a', 'b'), ('c', 'd'), ('a', 'c'), ('c', 'e')]
G.add_edges_from(edges)

# Draw graph G with vertices in red colour and edges in green


nx.draw(G, with_labels=True, node_color='red', edge_color='green',
node_size=800, font_size=12)
plt.title("Graph G")
plt.show()

# b) Add vertex f and edges {(b, f), (c, f)} to the graph
G.add_node('f')
G.add_edges_from([('b', 'f'), ('c', 'f')])

# Draw updated graph G1


nx.draw(G, with_labels=True, node_color='red', edge_color='green',
node_size=800, font_size=12)
plt.title("Updated Graph G1")
plt.show()

# Check if the new graph G1 is connected


is_connected = nx.is_connected(G)
print("Is G1 connected?:", is_connected)

# c) Find all paths from vertex b to f in the updated graph G1


paths = list(nx.all_simple_paths(G, source='b', target='f'))
print("\nAll paths from b to f in G1:")
for path in paths:
print(path)

Q.3

import networkx as nx
import matplotlib.pyplot as plt

# a) Draw regular graph on 8 vertices with degree 2 (Cycle graph


C8)
G1 = nx.cycle_graph(8)

# Draw the graph with labels and custom colors


nx.draw(G1, with_labels=True, node_color='skyblue',
edge_color='orange', node_size=800, font_size=12)
plt.title("Regular Graph C8 with Degree 2")
plt.show()

# b) Draw Petersen graph and check if it's 2-regular or 3-regular


G2 = nx.petersen_graph()

# Draw the Petersen graph


nx.draw(G2, with_labels=True, node_color='lightgreen',
edge_color='purple', node_size=800, font_size=12)
plt.title("Petersen Graph")
plt.show()

# Check the degree of each vertex in the Petersen graph


degrees = [deg for node, deg in G2.degree()]
print("Degrees of vertices in Petersen Graph:", degrees)

# The Petersen graph is 3-regular (each vertex has degree 3)

# c) Verify Handshaking Lemma for Petersen Graph


# The handshaking lemma: sum of degrees = 2 * number of
edges
sum_degrees = sum(degrees)
num_edges = G2.number_of_edges()
print(f"Sum of degrees: {sum_degrees}")
print(f"Number of edges: {num_edges}")
print(f"Verification: Sum of degrees == 2 * number of edges:
{sum_degrees == 2 * num_edges}")

You might also like