18ECL31-Data-Structures-Using-Python-Lab-Manual
18ECL31-Data-Structures-Using-Python-Lab-Manual
of ECE
Lab Code:18ECL31
Data Structures using Python Lab Manual
Contents
Vision
Mission
Vision
To produce globally competitive and socially responsible
Electronics and Communication Engineering graduates to
cater the ever changing needs of the society.
Mission
To provide quality education in the domain of
Electronics and Communication Engineering with
advanced pedagogical methods.
CO3
Develop non-linear data structures like trees and graphs.
CO4
Demonstrate traversal techniques on non-linear data structures.
1. SORTING TECHNIQUES
Aim:
Output:
enter list
elements
8465923
the length of list is: 7
the list elements before sorting ['8', '4', '6', '5', '9', '2', '3']
the list elements after sorting are ['2', '3', '4', '5', '6', '8', '9']
while(i<len(arr)-
1): j=i+1
while(j<len(arr
)):
if(arr[i]>arr[j]):
arr[i],arr[j]=arr[j],arr[i]
j=j+1
i=i+1
print(("the list elements after sorting"),arr)
Output:
enter the list
elements 54321
the lenght of list is: 5
the list elements before sorting ['5', '4', '3', '2', '1']
the list elements after sorting ['1', '2', '3', '4', '5']
Output:
enter the list elements 87602
array before sorting ['8', '7', '6', '0', '2']
array after sorting: ['0', '2', '6', '7', '8']
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
2. SORTING TECHNIQUES
Aim:
break
while(j<4):
M[k]=L2[j
] j+=1
k+=1
while(i<4):
M[k]=L1[i
] i+=1
k+=1
print("array after sorting:",M)
Output:
array after sorting: [1, 2, 3, 4, 5, 6, 7, 8]
print("before quicksort
the array is:",arr)
quicksort(arr,0,len(arr)-
1)
print("after quicksort
the array is:",arr)
Output:
enter list elements:
654321
before quicksort the array is: ['6', '5', '4', '3', '2', '1']
after quicksort the array is: ['1', '2', '3', '4', '5', '6']
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
3. SEARCHING TECHNIQUES
Aim:
Output:
enter the list
values 87654
enter a value to
find 5
the given value 5 is found in 3 th location
i=i+1
print("the list elements after sorting are",arr)
print("enter a value to search")
n=input()
flag=0
l=0
u=(len(arr)-1)
mid=int((l+u)
/2)
while(l<=u):
if(n==arr[mid]):
flag=1
print("the given number is found in the location",mid)
if(n<arr[mid]):
u=mid
-1 else:
l=mid+1
mid=int((l+u)
/2)
if(flag==0):
print("the element is not found in the list")
Output:
enter list
elements
321654
the length of list is: 6
the list elements before sorting ['3', '2', '1', '6', '5', '4']
the list elements after sorting are ['1', '2', '3', '4', '5',
'6'] enter a value to search
3
the given number is found in the location 2
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
Aim:
Source Code:
class node:
data=None
link=None
def append(self,num):
if(self.data==None):
self.data=num
self.link=None
else:
tr=node()
temp=node()
tr=self
while(tr.link!=None):
tr=tr.link
temp.data=num
temp.link=None
tr.link=temp
def display(self):
count=0
while(self!=None):
print(self.data)
count=count+1
self=self.link
print("the number of nodes in the linked list is",count)
def addatbeg(self,obj,num):
temp=node()
temp.data=num
temp.link=obj
obj=temp
return obj
def addafter(self,loc,num):
temp=node()
tr=node()
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
tr=self
for i in range(loc):
tr=tr.link
temp.data=num
temp.link=tr.link
tr.link=temp
def delete(self,obj,num):
old=node()
temp=node()
temp=self
while(temp!=None):
while(temp.data==num):
if(temp.data==self.data):
obj=self.link
else: old.link=temp.link
temp.data=None
temp.link=None
old=temp
temp=temp.link
return obj
obj=node()
obj.append(5)
obj.append(6)
obj.append(7)
obj.append(8)
print("the linkedlist after append")
obj.display()
obj=obj.addatbeg(obj,4)
obj=obj.addatbeg(obj,3)
print("after add at beg")
obj=obj.delete(obj,7)
obj.display()
obj.addafter(2,777)
obj.addafter(5,888)
print("after add after")
obj.display()
obj=obj.delete(obj,5)
print("the linked list after deletion")
obj.display()
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
Output:
the linked list after
append 5 6 7 8
the number of nodes in the linked
list is 4 after add at beg
3 4 5 6 8
the number of nodes in the linked
list is 5 after add after
3 4 5 777 6 8 888
the number of nodes in the linked
list is 7 the linked list after
deletion
3 4 777 6 8 888
the number of nodes in the linked list is 6
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
Aim:
Source Code:
class node:
data=None
prev=None
next=None
def append(self,n):
if(self.data==None):
self.data=n
self.prev=None
self.next=None
else:
temp=node()
temp.data=n
temp.next=None
tr=self
while(tr.next!=None):
tr=tr.next
tr.next=temp
temp.prev=tr
def addatbeg(self,n):
temp=node()
temp.data=n
temp.prev=None
temp.next=self
self.prev=temp
self=temp
return self
def display(self):
count=0
while(self!=None):
count=count+1
print(self.data)
self=self.next
print("the no of elements in linked list:",count)
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
def addafter(self,loc,n):
temp=node()
temp.data=n
tr=self
for i in range(loc):
tr=tr.next
temp.next=tr.nex
t temp.prev=tr
tr.next.prev=tem
p tr.next=temp
def delete(self,n):
temp=node()
old=node()
temp=self
while(temp!=None):
if(temp.data==n):
if(temp.data==self.data):
self=self.next
temp.next=None
self.prev=None
temp.data=None
else:
old.next=temp.next
temp.next.prev=old
temp.prev=None
temp.next=None
temp.data=None
else:
old=temp
temp=temp.next
return self
obj=node()
obj.append(5)
obj.append(6)
obj.append(7)
obj.append(8)
print("the linkedlist
after append")
obj.display()
obj=obj.addatbeg(3)
obj=obj.addatbeg(4)
print("after addatbeg")
obj.display()
obj.addafter(2,777)
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
obj.addafter(5,888)
print("after add after")
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
obj.display()
obj=obj.delete(5)
print("after deletion:")
obj.display()
Output:
the linkedlist after
append 5 6 7 8
the number of nodes in the
linkedlist is 4 after add at beg
3 4 5 6 8
the number of nodes in the
linkedlist is 5 after add after
3 4 5 777 6 8 888
the number of nodes in the
linkedlist is 7 the lnkedlist after
deletion
3 4 777 6 8 888
the number of nodes in the linkedlist is 6
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
Aim:
Source Code:
class node:
data=None
link=None
def append(self,n):
if(self.data==None):
self.data=n
self.link=self
else:
temp=node()
tr=node()
tr=self
while(tr.link!=self):
tr=tr.link
temp.data=n
temp.link=self
tr.link=temp
def display(self):
tr=self
if(self!=None):
print(self.data)
self=self.link
count=1
while(self!=tr):
count=count+1
print(self.data)
self=self.link
print("the no of nodes in linkedlist:",count)
def addatbeg(self,obj,n):
temp=node()
temp.data=n
temp.link=obj
tr=self
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
while(tr.link!=
self):
tr=tr.link
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
tr.link=temp
obj=temp
return obj
def addafter(self,loc,num):
temp=node()
tr=node()
tr=self
for i in range(loc):
tr=tr.link
temp.data=num
temp.link=tr.link
tr.link=temp
def delete(self,obj,n):
temp=node()
old=node()
tr=node()
tr=self
temp=self
while(temp!=None):
if(temp.data==n):
if(temp.data==self.data):
while(tr.link!=self):
tr=tr.link
obj=self.link
tr.link=obj
temp.data=None
temp.link=None
else:
old.link=temp.link
temp.data=None
temp.link=None
else:
old=temp
temp=temp.link
return obj
obj=node()
obj.append(5)
obj.append(6)
obj.append(7)
obj.append(8)
print("the linkedlist after
append")
obj.display()
obj=obj.addatbeg(obj,4)
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
obj=obj.addatbeg(obj,3)
print("after add at beg")
obj=obj.delete(obj,7)
obj.display()
obj.addafter(2,777)
obj.addafter(5,888)
print("after add after")
obj.display()
obj=obj.delete(obj,5)
print("the
linkedlist after
deletion")
obj.display()
Output:
the linkedlist after
append 5 6 7 8
the number of nodes in the
linkedlist is 4 after add at beg
3 4 5 6 8
the number of nodes in the
linkedlist is 5 after add after
3 4 5 777 6 8 888
the number of nodes in the
linkedlist is 7 the linked list after
deletion
3 4 777 6 8 888
the number of nodes in the linked list is 6
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
7. STACKS
Aim:
class stack:
arr=[ ]
top=-1
def push(self,n):
if(self.top==0):
self.top=self.top+1
self.arr.append(n)
if(self.top==len(self.arr)-1):
self.arr.append(n)
self.top=self.top+1
return
self.top=self.top+1
self.arr[self.top]=n
def pop(self):
if(self.top==-1):
print("stack is empty,we cant remove")
return
del_data=self.arr[self.top]
self.arr[self.top]=None
self.top=self.top-1
print("removed data is:",del_data)
print("stack elements are:",self.arr)
obj=stack()
obj.push(5)
obj.push(6)
obj.push(7)
obj.push(8)
print("the stack elements
are:",obj.arr)
obj.pop()
obj.pop()
obj.push(10)
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
obj.push(11)
print("the stack elements after
repushing are:",obj.arr)
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
Output:
the stack elements are: [5, 6,
6, 7, 8]
class node:
data=None
link=None
def push(self,n):
temp=node()
temp.data=n
temp.link=self
self=temp
return temp
def pop(self):
temp=self
self=self.link
temp.data=None
temp.link=None
return self
def display(self):
count=0
while(self.link!=None):
count=count+1
print(self.data)
self=self.link
print("the number of elements in
stack",count) obj=node()
obj=obj.push(4)
obj=obj.push(5)
obj=obj.push(6) print("the
actual stack is")
obj.display()
obj=obj.pop()
obj=obj.pop()
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
Output:
the actual stack is 6 5 4
the number of elements in
stack 3 the stack after
deletion
4
the number of elements in stack 1
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
8. QUEUES
Aim:
class queue:
arr=[]
front=-1
rear=-1
def enqueue(self,n):
if(self.rear==len(self.arr)-1):
self.front=0
self.rear=self.rear+1
self.arr.append(n)
return
self.rear=self.rear+1
self.front=0
self.arr[self.rear]=n
def dequeue(self):
if(self.arr==self.front==-1):
print("queue is empty")
return
else:
if(self.front==self.rear):
self.arr[self.front]=self.arr
[self.rear]=None self.front=-1
self.rear=-1
else:
self.arr[self.front]=None
self.front=self.front+1
obj=queue()
obj.enqueue(5)
obj.enqueue(6)
obj.enqueue(7)
obj.enqueue(8)
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
print(obj.arr)
obj.dequeue()
obj.dequeue()
obj.dequeue()
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
print(obj.arr)
obj.enqueue(9)
obj.enqueue(10)
obj.enqueue(11)
print(obj.arr)
Output
[5, 6, 7, 8]
[None, None, None, 8]
[None, None, None, 8, 9, 10, 11]
class node:
data=None
link=None
def enqueue(self,n):
if(self.data==None):
self.data=n
self.link=None
else:
temp=node()
tr=self
while(tr.link!=None):
tr=tr.link
temp.data=n
temp.link=None
tr.link=temp
def dequeue(self):
temp=self
self=self.link
temp.data=None
temp.link=None
return self
def display(self):
count=0
while(self!=None):
count=count+1
print(self.data)
self=self.link
print("the total number of elements in queue is:",count)
obj=node()
obj.enqueue(5)
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
obj.enqueue(6)
obj.enqueue(7)
print("the elements in queue are:")
obj.display()
obj=obj.dequeue()
obj=obj.dequeue()
print("the elements of queue after deleting:")
obj.display()
Output:
the elements in queue are:
56 7
the total number of elements in
queue is: 3 the elements of queue
after deleting:
7
the total number of elements in queue is: 1
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
Aim:
Source Code:
class node:
left=None
data=None
right=None
def buildtree(arr,n):
temp=node()
if(arr[n]!='\0'):
temp.left=buildtree(arr,2*n+1)
temp.data=arr[n]
temp.right=buildtree(arr,2*n+2)
return temp
def inorder(root):
if(root.data!=None):
inorder(root.left)
print(root.data)
inorder(root.right)
def preorder(root):
if(root.data!=None):
print(root.data)
preorder(root.left)
preorder(root.right)
def postorder(root):
if(root.data!=None):
postorder(root.left)
postorder(root.right)
print(root.data);
arr=['a','b','c','d','e','f','g','\0','\0','h','\0','\0','\0','\0','\0','\0','\0','\0','\
0','\0','\0']
root=node();
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
root=buildtree(ar
r,0);
print("\n inorder
traversel:\n");
inorder(root);
print("\n pre order
trvarsel:\n");
preorder(root);
print("\n post order
trvaresel:\n");
postorder(root);
Output:
inorder tvarulsel:
d b h e a fc g
pre order trvarsel:
a b d e h c f g
post order
trvaresel: d h e b
f g ca
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
Aim:
Source Code:
class node:
leftchild=None
data=None
rightchild=None
flag="Not found"
def insert(sr,num):
if(sr.data==None):
sr.leftchild=None
sr.data=num
sr.rightchild=None
else:
if(num<sr.data):
if(sr.leftchild==None):
sr.leftchild=node()
insert(sr.leftchild,num)
else:
insert(sr.leftchild,num)
else:
if(sr.rightchild==None):
sr.rightchild=node()
insert(sr.rightchild,num)
else:
insert(sr.rightchild,num)
def delete(root,num):
x=node()
xsucc=node()
par=node()
if(root==None):
print("tree is
empty.\n") return
par,x=search(root,num,par,x)
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
if(x.flag=="Not Found"):
print("data to be deleted , not found")
return
if(x.leftchild!=None and x.rightchild!=None):
par=x
xsucc=x.rightchild
while(xsucc.leftchild!=None):
par=xsucc
xsucc=xsucc.leftchild
x.data=xsucc.
data x=xsucc
if(x.leftchild==None and
x.rightchild==None):
if(par.rightchild==x):
par.rightchild=None
else:
par.leftchild=None
return
if(x.leftchild==None and
x.rightchild!=None):
if(par.leftchild==x):
par.leftchild=x.rightchild
else:
par.rightchild=x.rightchild
return
if(x.leftchild!=None and x.rightchild==None):
if(par.leftchild==x):
par.leftchild=x.leftchild
else:
par.rightchild=x.leftchild
return
def search(root,num,x,par):
q=root
while(q!=None):
if(q.data==num):
x.flag="Found"
x=q
print("\n the element :",x.data,"is
found")
return par,x
par=q
if(q.data>num):
q=q.leftchild
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
else:
q=q.rightchild
def inorder(sr):
if(sr!=None):
inorder(sr.leftchild)
print(sr.data)
inorder(sr.rightchild)
obj=node()
a=[11,9,13,8,10,12,14,15,
7]
for i in
range(9):
insert(obj,a[
i])
delete(obj,8)
print("\nbinary tree after the
deletion:\n") inorder(obj)
delete(obj,11)
print("\nbinary tree after the
deletion:\n") inorder(obj)
Output:
binary tree before the deletion:
7 8 9 10 11 12 13 14 15
('\n the element :', 10, 'is
found') binary tree after
the deletion:
7 8 9 11 12 13 14 15
('\n the element :', 14, 'is
found') binary tree after
the deletion:
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
7 8 9 11 12 13 15
('\n the element :', 8, 'is
found') binary tree after
the deletion: 7 9 11 12
13 15
('\n the element :', 11, 'is
found') binary tree after
the deletion:
7 9 12 13 15
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
Aim:
Source Code:
class Graph:
def init (self):
# dictionary containing keys that map to the corresponding
vertex object
self.vertices = {}
class Vertex:
def init (self,
key): self.key =
key self.points_to
= {}
def get_key(self):
"""Return key corresponding to this vertex
object.""" return self.key
def get_neighbours(self):
"""Return all vertices pointed to by this
vertex.""" return self.points_to.keys()
class Stack:
def init (self):
self.items = []
def is_empty(self):
return self.items
== []
def pop(self):
return self.items.pop()
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
def display_dfs(v):
visited = set()
s = Stack()
s.push(vertex)
while not s.is_empty():
current = s.pop()
if current in
visited:
continue
print(current.get_key(), end=' ')
visited.add(current)
for dest in current.get_neighbours():
if dest not in visited:
s.push(dest)
g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('dfs <vertex key>')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation ==
'add':
suboperation =
do[1]
if suboperation ==
'vertex': key =
int(do[2])
if key not in g:
g.add_vertex(k
ey)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src =
int(do[2])
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
dest =
int(do[3]) if
src not in g:
print('Vertex {} does not
exist.'.format(src)) elif dest not in g:
print('Vertex {} does not
exist.'.format(dest)) else:
if not g.does_edge_exist(src,
dest): g.add_edge(src, dest)
else:
print('Edge already exists.')
elif operation ==
'dfs': key =
int(do[1])
print('Depth-first Traversal: ',
end='') vertex =
g.get_vertex(key)
display_dfs(vertex)
print()
print('Edges: ')
for v in g:
for dest in
v.get_neighbours(): w =
v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
elif operation ==
'quit': break
Output:
What would you like to do? add vertex 1
What would you like to do? add vertex 2
What would you like to do? add vertex 3
What would you like to do? add vertex 4
What would you like to do? add vertex 5
18ECL31 Data Structures Using Python Lab Manual Dept. of ECE
Aim:
Source Code:
class Graph:
def init (self):
# dictionary containing keys that map to the corresponding vertex
object
self.vertices = {}
47
18ECL31 Data Structures using Python Lab Manual Dept. of ECE
return
self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
class Vertex:
def init (self, key):
self.key = key
self.points_to = {}
def get_key(self):
"""Return key corresponding to this vertex
object.""" return self.key
def get_neighbours(self):
"""Return all vertices pointed to by this vertex."""
return self.points_to.keys()
class Queue:
def init (self):
self.items = []
def is_empty(self):
return self.items == []
48
18ECL31 Data Structures using Python Lab Manual Dept. of ECE
self.items.append(data)
def dequeue(self):
return self.items.pop(0)
def display_bfs(vertex):
"""Display BFS Traversal starting at vertex."""
visited = set()
q = Queue()
q.enqueue(vertex)
visited.add(vertex)
while not q.is_empty():
current = q.dequeue()
print(current.get_key(), end='
')
for dest in
current.get_neighbours(): if dest
not in visited:
visited.add(dest)
q.enqueue(dest)
g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src>
<dest>') print('bfs <vertex
key>') print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation ==
'vertex': key = int(do[2])
if key not in g:
49
18ECL31 Data Structures using Python Lab Manual Dept. of ECE
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3]) if
src not in g:
print('Vertex {} does not
exist.'.format(src)) elif dest not in g:
print('Vertex {} does not
exist.'.format(dest)) else:
if not g.does_edge_exist(src,
dest): g.add_edge(src, dest)
else:
print('Edge already
exists.') elif operation == 'bfs':
key = int(do[1])
print('Breadth-first Traversal: ',
end='') vertex = g.get_vertex(key)
display_bfs(vertex)
print()
elif operation == 'display':
print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in
v.get_neighbours(): w =
v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
50
18ECL31 Data Structures using Python Lab Manual Dept. of ECE
Output:
What would you like to do? add vertex 1
What would you like to do? add vertex 2
What would you like to do? add vertex 3
What would you like to do? add vertex 4
What would you like to do? add vertex 5
What would you like to do? add vertex 6
What would you like to do? add vertex 7
What would you like to do? add vertex 8
What would you like to do? add vertex 9
What would you like to do? add vertex 10
What would you like to do? add edge 1 2
What would you like to do? add edge 1 3
What would you like to do? add edge 1 5
What would you like to do? add edge 2 6
What would you like to do? add edge 3 7
What would you like to do? add edge 3 8
What would you like to do? add edge 4 8
What would you like to do? add edge 8 10
What would you like to do? add edge 5 10
What would you like to do? add edge 6 9
What would you like to do? add edge 9 10
What would you like to do? bfs 1
Breadth-first Traversal: 1 3 2 5 7 8 6 10 9
What would you like to do? quit
51