Practical 1
Practical 1
ASSIGNMENT 1
QUESTION NO.1]Generate graph G with vertex(node) set {1,2,3,4,5} and the edge set {(1,5),
(1,3),(1,2),(2,3),(2,4), (3,4), (4,5)} . Draw graph G
In [2]: G1=nx.Graph()
G1.add_edges_from([(1,5),(1,3),(1,2),(2,3),(2,4),(3,4),(4,5)])
nx.draw(G1,with_labels=True)
plt.show()
QUESTION NO.2]Generate graph G1 with vertex set { ‘a’,’b’,’c’,’d’} and the edge set {x=(‘a’,
’d’), y=(’b’,’c’), z=( ’b’,’’d’), w =( ‘a’,’c’)}. Draw graph G1 showing labeled vertices and edges
In [3]: G1=nx.Graph()
G1.add_edges_from([('a','d'),('b','c'),('b','d'),('a','c')])
w={('a','d'):'x',('b','c'):'y',('b','d'):'z',('a','c'):'w'}
pos=nx.spring_layout(G1)
nx.draw(G1,pos,with_labels=True)
nx.draw_networkx_edge_labels(G1,pos,edge_labels=w)
plt.show()
QUESTION NO.3]Generate graph G2 with vertex set {1,2,3,4,5} and edge set {(4,5),(5,3), (2, 2),
(2,3),(2,4), (3,4), (1,5)} . Draw graph G2 with vertices in red colour and edges in green.
In [4]: G1=nx.Graph()
G1.add_edges_from([(4,5),(5,3),(2,2),(2,3),(2,4),(3,4),(1,5)])
nx.draw(G1,with_labels=True,node_color="red",edge_color="green")
plt.show()
QUESTION NO.4]Generate graph G3 with vertex set {1,2,3,4,5,6,7,8} and the edge set {x=(1,3),
y=(3,2), z=(2,5), w=(5,7), v=(7,8), U=(8,4), T=(4,1)}.Draw graph G3 showing labeled vertices
and edges.Draw graph G3 with vertices in skyblue colour and edges in yellow.
In [7]: G3=nx.Graph()
G3.add_edges_from([(1,3),(3,2),(2,5),(5,7),(7,8),(8,4),(4,1)])
W={(1,3):'x',(3,2):'y',(2,5):'z',(5,7):'w',(7,8):'v',(8,4):'U',(4,1):'T'}
pos=nx.spring_layout(G3)
nx.draw(G3,pos,with_labels=True,node_color="skyblue",edge_color="yellow")
nx.draw_networkx_edge_labels(G3,pos,edge_labels=W)
plt.show()
QUESTION NO.5]Find the number of vertices, number of edges and degrees of all vertices in
above graphs.
In [10]: vertices=list(G1.nodes())
print(vertices)
[4, 5, 3, 2, 1]
In [11]: Edges=list(G1.edges())
print(Edges)
[(4, 5), (4, 2), (4, 3), (5, 3), (5, 1), (3, 2), (2, 2)]
In [12]: degree=dict(G1.degree())
print(degree)
{4: 3, 5: 3, 3: 3, 2: 4, 1: 1}
Vertex4: Degree3
Vertex5: Degree3
Vertex3: Degree3
Vertex2: Degree4
Vertex1: Degree1
In [17]: deg_sum=sum(dict(G3.degree()).values())
twice_edges=2*G3.number_of_edges()
if deg_sum==twice_edges:
print("Hand shaking lemma verified")
else:
print("Hand shaking lemma not verified")