Data Structure Lab
Data Structure Lab
LABORATORY MANUAL
1
EX. NO DATE LIST OF EXPERIMENT PAGE NO STAFF SIGN
10
11
12
13
14
15
16
17
18
2
Ex.No: 1 IMPLEMENTATION OF SIMPLE CLASS PROGRAM
Aim:
To Write a Python program to implement the simple class program using
inheritance.
Algorithm:
Step1:Start.
Step 3: Create a built-in-function with reference parameter and get the no.of sides for the
polygon.
Step 6: Print.
Step7:Stop.
Program:
class polygon:
def init (self,no_of_sides):
self.n=no_of_sides
self.sides=[0 for i in range(no_of_sides)]
def inputside(self):
self.sides=[float(input("Enter side"+str(i+1)+":"))for i in range(self.n)] def
dispsides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])
class triangle(polygon):
def init (self):
polygon. init (self,3)
3
def findarea(self):
a,b,c=self.sides
s=(a+b+c)/2
area=(s*(s-a)*(s-b)*(s-c))**0.5
print("The area of the triangle is %0.2f” %area)
Output:
>>> t=triangle()
>>> t.inputside()
Enter side1:3 Enter
side2:5 Enter
side3:4
>>> t.dispsides()
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0
>>> t.findarea()
The area of the triangle is 6.00
Result:
Thus the Python class program was implemented using inheritance concept were
executed successfully.
4
Ex.No: 2 IMPLEMENTATION OF RECURSION ALGORITHM
Aim:
To Write a Python program
a) To find the Fibonacci series using recursion.
b) To find the factorial of number using recursion.
Step1: Start.
Step 2: Define a function.
Step 3: Check the number is less than or equal to 1.
Step 4: If it is equal to 1 return it.
Step5: Else use the formula (recur_fibo(n1)+recur_fibo(n-2)).
Step6: Given the number of terms to be print.
Step 7: Print.
Step 8: Stop.
Program:
def recur_fibo(n):
if n<=1:
return n
else:
return(recur_fibo(n-1)+recur_fibo(n-2))
nterms=10
if nterms<=0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence :") for
i in range(nterms):
print(recur_fibo(i))
5
Output:
Fibonacci sequence :
0
1
1
2
3
5
8
13
21
34
Step1:Start.
Step2:Define a function.
Step3: Check the number is equal to 1.
Step4:If it is equal to 1
Step5:Else use the formula(X*factorial(X-1))
Step6: Give the number to be factorial.
Step7:Print.
Step8:Stop.
Program:
def factorial(x):
x==1:
return 1
else:
return (x*factorial(x-1))
num=3
6
Output:
The factorial of 3 is 6
Result:
Thus the recursion algorithm was implemented using Python program were executed
successfully.
7
Ex.No: 3 IMPLEMENTATION THE PYTHON ARRAY USING LIST
Aim:
To write a Python program for implement the array to insert, delete and traverse the data
element.
Algorithm:
Step1: Start.
Step 2: Import array library.
Step3: Print the array values and then accessing the array element from index 2.
Step4: Insert an element in the array of index 3 & 4 (400,150) respectively and then
print the inserted element .
Step5: Delete an element from the array (150) and then print .
Step 6: Traversing the elements from the array and then print .
Step 7: Stop.
Program:
import array
print(balance[2])
balance.insert(3, 400)
balance.insert(4, 150)
8
print(balance)
print(balance.index(400))
balance.remove(150)
print(balance)
Output:
The array given values
------------Inserting an element------------
After Insertion :
9
Traverse an array
Array Elememt :
100
Array Elememt :
200
Array Elememt :
300
Array Elememt :
400
Result:
Thus the Python program executed successfully.
10
Ex. No:4 IMPLEMENTATION OF LINKED LIST
Aim:
To write a python program to implement the linked list.
Algorithm:
Step1: Start .
Step2:Creating a class as Node.
Step10: Stop.
Program:
class Node:
def init (self, data = None, next=None):
self.data = data
self.next = next
class LinkedList:
def init (self): self.head
= None
def insert(self, data):
newNode = Node(data)
if(self.head):
current = self.head
11
while(current.next):
current = current.next
current.next = newNode
else:
self.head = newNode
def printLL(self):
current = self.head
while(current):
print(current.data)
current = current.next
print("The data elements in linked list are: \n ") LL
= LinkedList()
LL.insert(1)
LL.insert(2)
LL.insert(3)
LL.insert(4)
LL.printLL()
12
Output:
Result:
13
Ex. No: 5 IMPLEMENTATION OF STACK ADT
Aim:
To write a Python program to implement of stack ADT using list.
Algorithm:
Step1: Start.
Step2: Creating a class as Node.
push function.
Step5: Defining pop function.
Step 8: Print.
Step 11: Get the input from the user for choice and then print. Step
12: Stop.
14
Program:
class Node:
def init (self,data):
self.data=data
self.next=None
class Stack:
def init (self):
self.head=None
self.ctr=0
self.top=None
def Push(self,data):
node=Node(data) if
self.head==None:
self.head=node
self.top=node
else:
self.top.next=node self.top=node
print("Node pushed to stack",data)
self.ctr+=1
return def
Pop(self):
if self.head==None: print("Stack
Underflow")
elif self.head==self.top:
print("Deleted from Stack",self.head.data)
self.head=self.top=None
self.ctr-=1
else:
print("Deleted from Stack",self.top.data)
temp=self.head
while temp.next is not self.top:
temp=temp.next
temp.next=None
self.top=temp
self.ctr-=1
return
def Traverse(self):
if self.head==None:
print("No Nodes exist")
return
temp=self.head
while temp is not None:
print(temp.data)
temp=temp.next
def Menu():
print("1.Push\n2.Pop\n3.Traverse\n4.Number of nodes\n5.Exit")
ch=int(input("Enter choice:"))
15
return ch
s=Stack()
print("**************Stack****************
*") while True:
ch=Menu()
if ch==1:
data=input("Enter data:")
s.Push(data)
elif ch==2:
s.Pop()
elif ch==3:
s.Traverse()
elif ch==4:
print("Number of nodes",s.ctr)
else:
print('Quit')
break
Output:
**************Stack*****************
1.Push
2.Pop
3.Traverse
4.Number of nodes
5.Exit
Enter choice:1
Enter data:12
1.Push
2.Pop
3.Traverse
4.Number of nodes
5.Exit
Enter choice:1 Enter
data:123
Node pushed to stack 123
1.Push
2. Pop
16
3. Traverse
4.Number of nodes
5.Exit
Enter choice:2
Deleted from Stack 123
1.Push
2.Pop
3.Traverse
4.Number of nodes
5.Exit
Enter choice:3
12
123
1.Push
2.Pop
3.Traverse
4.Number of nodes
5.Exit
Enter choice:4
Number of nodes 1
1.Push
2.Pop
3.Traverse
4.Number of nodes
5.Exit
Enter choice:5
Quit
Result:
17
Ex. No: 6 IMPLEMENTATION OF QUEUE ADT
Aim:
Write a Python program of implementation of queue.
Algorithm:
Step1: Start.
Step2:Create a empty queue.
Program:
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued fromqueue") print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)
18
Output:
Initial queue
['a', 'b', 'c']
Result:
19
Ex. No: 7 APPLICATION OF LIST(POLYNOMIAL)
Aim:
To write a Python program to find the polynomial.
Algorithm:
Step1: Start.
Step2:Creating a class as Node.
Step3:Define addnode.
Step4:Define printList.
Step5:Define remove Duplicate.
Step6:Define multiply.
Step7: Print 1st polynomial.
Step8:Print 2nd polynomial.
Program:
class Node:
def init (self):
self.coeff = None
self.power = None
self.next = None
def addnode(start, coeff, power):
newnode = Node();
newnode.coeff = coeff;
newnode.power = power;
newnode.next = None;
if (start == None):
return newnode;
ptr = start;
while (ptr.next != None):
ptr = ptr.next;
ptr.next = newnode;
return start;
def printList(ptr):
while (ptr.next != None):
20
print(str(ptr.coeff) + 'x^' + str(ptr.power), end = '')
if( ptr.next != None and ptr.next.coeff >= 0):
print('+', end = '')
ptr = ptr.next
print(ptr.coeff)
def removeDuplicates(start):
ptr2 = None
dup = None
ptr1 = start;
while (ptr1 != None and ptr1.next != None):
ptr2 = ptr1;
while (ptr2.next != None):
if (ptr1.power == ptr2.next.power):
ptr1.coeff = ptr1.coeff + ptr2.next.coeff;
dup = ptr2.next;
ptr2.next = ptr2.next.next;
else:
ptr2 = ptr2.next;
ptr1 = ptr1.next;
def multiply(poly1, Npoly2, poly3):
ptr1 = poly1;
ptr2 = poly2;
while (ptr1 != None):
while (ptr2 != None):
coeff = ptr1.coeff * ptr2.coeff;
power = ptr1.power + ptr2.power;
poly3 = addnode(poly3, coeff, power);
ptr2 = ptr2.next;
ptr2 = poly2;
ptr1 = ptr1.next;
removeDuplicates(poly3);
return poly3;
if name ==' main ':
poly1 = None
poly2 = None
poly3 = None;
poly1 = addnode(poly1, 3, 3);
poly1 = addnode(poly1, 6, 1);
poly1 = addnode(poly1, -9, 0);
poly2 = addnode(poly2, 9, 3);
poly2 = addnode(poly2, -8, 2);
poly2 = addnode(poly2, 7, 1);
poly2 = addnode(poly2, 2, 0);
print("1st Polynomial:- ", end = '');
printList(poly1);
print("2nd Polynomial:- ", end = '');
printList(poly2);
poly3 = multiply(poly1, poly2, poly3);
print("Resultant Polynomial:- ", end = '');
printList(poly3);
21
Output:
Result:
22
Ex. No: 8 IMPLEMENT THE BUBBLE SORT
Aim:
To write a Python program to sort the elements using bubblesort.
Algorithm:
Step1: Start.
Step2: Define bubble_sort.
Step 3: For i in range(0,len(list1)-1)
Step 7: Stop.
Program:
def bubble_sort(list1):
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
temp = list1[j]
list1[j] = list1[j+1]
list1[j+1] = temp
return list1
list1 = [5, 3, 8, 6, 7, 2]
print("The unsorted list is: ", list1) print("The
sorted list is: ", bubble_sort(list1))
23
Output:
Result:
24
Ex. No: 9 IMPLEMENT THE INSERTIONSORT
Aim:
To write a Python program to sort the elements using insertion sort.
Algorithm:
Step1: Start.
Step2: Define insertion_sort.
Step 3: For i in range(1,len(alist)).
Step4: Get the input from the user to enter the list of numbers.
Step 6: Stop.
Program:
def insertion_sort(alist):
for i in range(1,len(alist)):
temp=alist[i]
j=i-1
while(j>=0 and temp<alist[j]):
alist[j+1]=alist[j]
j=j-1
alist[j+1]=temp
alist=input('Enter the list of numbers :').split()
alist=[int(x)for x in alist]
insertion_sort(alist) print('Sorted
list :',end='') print(alist)
25
Output:
Result:
26
Ex.N0: 10 IMPLEMENT THE QUICKSORT
Aim:
To write a Python program to sort elements using quick sort method.
Algorithm:
Step1:Start. Step2:Define
quicksort. Step3:Define
partition.
Step4: Get the input from the user to enter the list of numbers.
Step5:Print the sorted list.
Step 6:Stop.
Program:
def quicksort(alist,start,end):
"""Sorts the list from indexes start to end-1 inclusive.""" if
end-start>1:
p=partition(alist,start,end)
quicksort(alist,start,p) quicksort(alist,p+1,end)
def partition(alist,start,end):
pivot=alist[start] i=start+1
j=end-1
while True:
while(i<=j and alist[i] <=pivot):
i=i+1
while(i<=j and alist[j] >=pivot):
j=j-1
if i<=j:
alist[i],alist[j]=alist[j],alist[i] else:
alist[start],alist[j]=alist[j],alist[start] return j
alist=input('Enter the list of numbers :').split()
alist=[int(x)for x in alist]
quicksort(alist,0,len(alist))
27
print('Sorted list :',end='')
print(alist)
Output:
Result:
28
Ex.N0:11 IMPLEMENT THE BINARY SEARCH
Aim
:
To write a Python program to search an element in a list of elements using Binary
Search technique.
Algorithm:
Step1:Start. Step2:Define
binary_sort.
Step3:Get the input from the user to enter the size of the list.
Step4:Again get the input from the user to enter any number.
Step 5: Print the list will be sorted
Step6: Get the input from the user to enter the number to be searched.
Step7:Print the entered number which is present at the position.
Step8: Stop.
Program:
def binary_sort(sorted_list,length,key):
start=0
end=length-1 while
start<=end:
mid=int((start+end)/2) if
key==sorted_list[mid]:
print("\n Entered number %d is present at position : %d" %(key,mid))
return-1
elif key<sorted_list[mid]:
end=mid-1
elif key>sorted_list[mid]:
start=mid+1
print("\n Elementnot found!")
29
return-1
lst=[]
size=int(input("Enter size of list :\t"))
for n in range(size):
numbers=int(input("Enter any number :\t"))
lst.append(numbers)
lst.sort()
print('\n\n The list will be sorted,the sorted list is :',lst)
x=int(input("\n Enter the number to be search :"))
binary_sort(lst,size,x)
Output:
Enter size of list : 3
Enter any number : 2
Enter any number : 8
Enter any number : 22
Result:
30
Ex.N0:12 IMPLEMENT THE HASH TABLE
Aim:
To write a Python program to implement the hash table.
Algorithm:
Step1:Start.
Step2:Define display_hash.
Step3:For i in range(len(hashtable)).
Step4:Print.
Step 5: Define Hashing.
Step6:Define insert .
Step7:display_hash(hashtable). Step8:
Stop.
Program:
def display_hash(hashtable): for i
in range(len(hashtable)):
print(i,end="")
for j in hashtable[i]:
print("-->",end="")
print(j,end="")
print()
hashtable=[[]for _ in range(10)]
def Hashing(keyvalue):
return keyvalue % len(hashtable) def
insert(hashtable,keyvalue,value):
hash_key=Hashing(keyvalue)
hashtable[hash_key].append(value)
insert(hashtable,0,"Allahabad")
insert(hashtable,5,"Mumbai")
insert(hashtable,3,"Mathura")
insert(hashtable,9,"Delhi")
insert(hashtable,1,"Punjab")
insert(hashtable,1,"Noida")
display_hash(hashtable)
31
Output:
0--> Allahabad
1--> Punjab--> Noida
2
3--> Mathura
4
5--> Mumbai
6
7
8
9--> Delhi
Result:
32
Ex.N0:13 IMPLEMENT THE TREE TRAVERSAL
Aim:
To write a Python program to implement the tree traversal.
Algorithm:
Step1:Start.
Step2:Creating a class as Node.
Step 9: Stop.
Program:
class Node:
def init (self, key):
self.left = None
self.right = None
self.val = key
def printInorder(root): if
root:
printInorder(root.left) print(root.val),
printInorder(root.right)
def printPostorder(root): if
root:
printPostorder(root.left)
printPostorder(root.right) print(root.val),
def printPreorder(root): if
root:
print(root.val), printPreorder(root.left)
printPreorder(root.right)
33
root = Node(1) root.left
= Node(2) root.right =
Node(3) root.left.left =
Node(4)
root.left.right = Node(5)
print ("\nPreorder traversal of binary tree is")
printPreorder(root)
print ("\nInorder traversal of binary tree is")
printInorder(root)
print ("\nPostorder traversal of binary tree is")
printPostorder(root)
Output:
Result:
34
Ex.N0:14 IMPLEMENT THE BINARY SEARCH TREE
Aim:
To write a Python program to implement the binary search tree.
Algorithm:
Step1:Start.
Step2:Creating a class as BTSNode.
Program:
class BSTNode:
def init (self, key):
self.key = key
self.left = None
self.right = None
self.parent = None
def insert(self, node):
35
if self.key > node.key:
if self.left is None:
self.left = node
node.parent = self
else:
self.left.insert(node) elif
self.key < node.key:
if self.right is None:
self.right = node
node.parent = self
else:
self.right.insert(node) def
inorder(self):
if self.left is not None:
self.left.inorder()
print(self.key, end=' ') if
self.right is not None:
self.right.inorder()
def replace_node_of_parent(self, new_node): if
self.parent is not None:
if new_node is not None:
new_node.parent = self.parent
if self.parent.left == self:
self.parent.left = new_node
elif self.parent.right == self: self.parent.right
= new_node
else:
self.key = new_node.key
self.left = new_node.left
self.right = new_node.right if
new_node.left is not None:
new_node.left.parent = self if
new_node.right is not None:
new_node.right.parent = self
def find_min(self):
current = self
while current.left is not None:
current = current.left
return current
def remove(self):
if (self.left is not None and self.right is not None):
successor = self.right.find_min()
self.key = successor.key successor.remove()
elif self.left is not None:
self.replace_node_of_parent(self.left)
elif self.right is not None:
self.replace_node_of_parent(self.right)
else:
36
self.replace_node_of_parent(None)
def search(self, key):
if self.key > key:
if self.left is not None:
return self.left.search(key) else:
return None
elif self.key < key:
if self.right is not None:
return self.right.search(key) else:
return None
return self
class BSTree:
def init (self):
self.root = None
def inorder(self):
if self.root is not None:
self.root.inorder()
def add(self, key):
new_node = BSTNode(key)
if self.root is None:
self.root = new_node
else:
self.root.insert(new_node)
def remove(self, key):
to_remove = self.search(key) if
(self.root == to_remove
and self.root.left is None and self.root.right is None):
self.root = None
else:
to_remove.remove() def
search(self, key):
if self.root is not None:
return self.root.search(key) bstree
= BSTree()
print('Menu (this assumes no duplicate keys)')
print('add <key>')
print('remove <key>')
print('inorder')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
key = int(do[1])
bstree.add(key)
elif operation == 'remove':
key = int(do[1])
37
bstree.remove(key)
elif operation == 'inorder':
print('Inorder traversal: ', end='')
bstree.inorder()
print()
elif operation == 'quit':
break
Output:
Result:
38
Ex.N0:15 IMPLEMENTATION OF HEAP
Aim:
To write a Python program toimplement the heap.
Algorithm:
Step1:Start.
Step2: Import heapq library.
Program:
import heapq
li=[5, 7, 9, 1, 3]
heapq.heapify(li)
print("The created heap is : ",end="") print(list(li))
heapq.heappush(li,4)
print("The modified heap after push is : ",end="") print(list(li))
print("The popped and smallest element is : ",end="")
print(heapq.heappop(li))
39
Output:
Result:
40
Ex.N0:16 IMPLEMENTATION OF GRAPH REPRESENTATION
Aim:
To write a Python program toimplement the graph representation.
Algorithm:
Step1:Start. Step2:Import
default dict.
Program:
from collections import defaultdict
graph = defaultdict(list)
def addEdge(graph,u,v):
graph[u].append(v)
def generate_edges(graph):
edges = []
for node in graph:
for neighbour in graph[node]:
edges.append((node, neighbour))
return edges
addEdge(graph,'a','c')
addEdge(graph,'b','c')
addEdge(graph,'b','e')
addEdge(graph,'c','d')
addEdge(graph,'c','e')
addEdge(graph,'c','a')
addEdge(graph,'c','b')
addEdge(graph,'e','b')
addEdge(graph,'d','c')
41
addEdge(graph,'e','c') print(generate_edges(graph))
Output:
[('a', 'c'), ('b', 'c'), ('b', 'e'), ('c', 'd'), ('c', 'e'), ('c', 'a'), ('c', 'b'), ('e', 'b'), ('e', 'c'), ('d', 'c')]
Result:
42
Ex.N0:17 IMPLEMENTATION OF SHORTEST PATH ALGORITHM
Aim:
To write a Python program to implement the shortest path algorithm.
Algorithm:
Step1:Start.
Step2:Creating a class as graph.
Program:
43
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
u = self.minDistance(dist, sptSet) sptSet[u]
= True
for v in range(self.V):
if self.graph[u][v] > 0 and sptSet[v] == False and dist[v] > dist[u] + self.graph[u][v]:
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist) g
= Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
g.dijkstra(0)
Output:
Result:
44
Ex.N0:18 IMPLEMENT THE MINIMUM SPANNING TREE ALGORITHM
Aim:
To write a Python program to implement the minimum spanning tree algorithm.
Algorithm:
Step1:Start. Step2:Import
default dict.
Program:
45
else:
parent[yroot] = xroot rank[xroot]
+= 1
def KruskalMST(self):
result = []
i=0
e=0
self.graph = sorted(self.graph,key=lambda item: item[2]) parent =
[]
rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V - 1:
u, v, w = self.graph[i]
i= i+1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e = e + 1
result.append([u, v, w])
self.union(parent, rank, x, y)
minimumCost = 0
print ("Edges in the constructed MST")
for u, v, weight in result:
minimumCost += weight
print("%d -- %d == %d" % (u, v, weight))
print("Minimum Spanning Tree" , minimumCost)
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
g.KruskalMST()
46
Output:
Result:
47