ANAND INSTITUTE OFHIGHER TECHNOLOGY
KAZHIPATTUR, CHENNAI–603 103
DEPARTMENT OF ARTIFICIAL ENGINEERING AND DATA SCIENCE
II SEMESTER-2017 REGULATION
AD8261–DATA STRUCTURE DESIGN LABORATORY
LAB MANUAL
INDEX
Date Name of the experiment Page
Ex:
no
12/4/21 Implementation of simple class program. 1
1.
2. 19/4/21 Implementation of recursive algorithm. 3
3. 26/4/21 Implement the python array using list. 6
4. 3/5/21 Implementation of linked list. 9
5. 10/5/21 Implementation of stack ADT. 12
17/5/21 Implementation of queue ADT. 16
6.
24/5/21 Compute the polynomial numbers. 18
7.
8. 31/5/21 Implement the bubble sorting. 21
9. 31/5/21 Implement the insertion sorting. 23
10. 31/5/21 Implement the quick sorting. 25
11. 7/6/21 Implement the binary search. 27
12. 7/6/21 Implement the hash table. 29
13. 14/6/21 Implement the tree traversal. 31
14. 14/6/21 Implement the binary search tree. 33
15. 21/6/21 Implement the heap. 37
16. 21/6/21 Implement the graph representation. 39
17. 28/6/21 Implement the shortest path algorithm. 41
18. 5/7/21 Implement the minimum spanning algorithm. 44
[Link]: 1 IMPLEMENTATION OF SIMPLE CLASS PROGRAM
Date: 12/4/21
Aim:
Write a Python class program to implement the simple class program using
Inheritance
Algorithm:
Step1:Start.
Step2: Create a class.
Step 3: Create a built-in-function with reference parameter and get the [Link] sides for the
polygon.
Step4: Create a user-define function to print the sides.
Step5: Create a derived class.
Step 6: Print.
Step7:Stop.
Program:
class polygon:
def __init__(self,no_of_sides):
self.n=no_of_sides
[Link]=[0 for i in range(no_of_sides)]
def inputside(self):
[Link]=[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",[Link][i])
class triangle(polygon):
def __init__(self):
polygon.__init__(self,3)
def findarea(self):
1
a,b,c=[Link]
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()
>>> [Link]()
Enter side1:3
Enter side2:5
Enter side3:4
>>> [Link]()
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0
>>> [Link]()
The area of the triangle is 6.00
Result:
Thus the Python classprogram was implemented using inheritance concept were
executed successfully.
2
[Link]: 2 IMPLEMENTATION OF RECURSION ALGORITHM
Date: 19/4/21
Aim:
Write a Python program
a) To find the fibonacci series using recursion.
b) To find the factorial of number using recursion.
A) Algorithm: To find the fibonacci series 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))
3
Output:
Fibonacci sequence :
0
1
1
2
3
5
8
13
21
34
B) Algorithm:To find the factorial of number using recursion.
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):
"""This is a recursive function to find the factorial of an integer"""
if x==1:
return 1
else:
return (x*factorial(x-1))
num=3
print("The factorial of",num,"is",factorial(num))
4
Output:
The factorial of 3 is 6
Result:
Thus the recursion algorithm was implemented using Python program
wereexecuted successfully.
5
[Link]: 3 IMPLEMENTA THE PYTHON ARRAY USING LIST
Date: 26/4/21
Aim:
Write a Python program for implement the python 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
balance = [Link]('i', [100,200,300])
print("The array given values")
print(balance)
print("Accessing of an array element from index[2] : ")
print(balance[2])
print(" ------------Inserting an element------------")
[Link](3, 400)
[Link](4, 150)
print("After Insertion :")
6
print(balance)
print("Accessing the index value of an element :")
print([Link](400))
print(" -------------------Deleting an element from a array-----------")
[Link](150)
print(balance)
print( " --------------------Traverse an array ----------- ")
for x in balance:
print("Array Elememt :")
print(x)
Output:
The array given values
array('i', [100, 200, 300])
Accessing of an array element from index[2] :
300
------------Inserting an element------------
After Insertion :
array('i', [100, 200, 300, 400, 150])
Accessing the index value of an element :
3
7
-------------------Deleting an element from a array-----------
array('i', [100, 200, 300, 400])
--------------------Traverse an array -----------
Array Elememt :
100
Array Elememt :
200
Array Elememt :
300
Array Elememt :
400
Result:
Thus the python array was implemented using Python library were executed successfully.
8
[Link]: 4 IMPLEMENTATION OF LINKED LIST
Date: 3/5/21
Aim:
To write a python program to implement the linked list.
Algorithm:
Step1: Start .
Step2: Creating a class as Node.
Step 3: Again creating a class as Linked List.
Step4: Defining an insert function.
Step 5: Defining printLL .
Step 6: Print the data element in the linked list.
Step7: Creating an object for the class Linked List .
Step 8: With the help of the object calling the insert function to insert the element.
Step 9: Print the data element.
Step10: Stop.
Program:
class Node:
def __init__(self, data = None, next=None):
[Link] = data
[Link] = next
class LinkedList:
def __init__(self):
[Link] = None
def insert(self, data):
newNode = Node(data)
if([Link]):
current = [Link]
while([Link]):
current = [Link]
9
[Link] = newNode
else:
[Link] = newNode
def printLL(self):
current = [Link]
while(current):
print([Link])
current = [Link]
print("The data elements in linked list are: \n ")
LL = LinkedList()
[Link](1)
[Link](2)
[Link](3)
[Link](4)
[Link]()
10
Output:
The data elements in linked list are:
Result:
Thus the Python program executed successfully.
11
[Link]: 5 IMPLEMENTATION OF STACK ADT
Date: 10/5/21
Aim:
Write a Python program to implement of stack ADT using list.
Algorithm:
Step1: Start.
Step2: Creating a class as Node.
Step 3: Again creating a class as Stack.
Step4: Defining push function.
Step5: Defining pop function.
Step6: Defining traverse function.
Step 7: Define Menu function.
Step 8: Print.
Step 9: Creating an object for the class Stack.
Step 10: Print the stack.
Step 11: Get the input from the user for choice and then print.
Step 12: Stop.
12
Program:
class Node:
def __init__(self,data):
[Link]=data
[Link]=None
class Stack:
def __init__(self):
[Link]=None
[Link]=0
[Link]=None
def Push(self,data):
node=Node(data)
if [Link]==None:
[Link]=node
[Link]=node
else:
[Link]=node
[Link]=node
print("Node pushed to stack",data)
[Link]+=1
return
def Pop(self):
if [Link]==None:
print("Stack Underflow")
elif [Link]==[Link]:
print("Deleted from Stack",[Link])
[Link]=[Link]=None
[Link]-=1
else:
print("Deleted from Stack",[Link])
temp=[Link]
while [Link] is not [Link]:
temp=[Link]
[Link]=None
[Link]=temp
[Link]-=1
return
def Traverse(self):
if [Link]==None:
print("No Nodes exist")
return
temp=[Link]
while temp is not None:
print([Link])
temp=[Link]
def Menu():
print("[Link]\[Link]\[Link]\[Link] of nodes\[Link]")
ch=int(input("Enter choice:"))
return ch
13
s=Stack()
print("**************Stack*****************")
while True:
ch=Menu()
if ch==1:
data=input("Enter data:")
[Link](data)
elif ch==2:
[Link]()
elif ch==3:
[Link]()
elif ch==4:
print("Number of nodes",[Link])
else:
print('Quit')
break
Output:
**************Stack***************
**
[Link]
[Link]
[Link]
[Link] of nodes
[Link]
Enter choice:1
Enter data:12
[Link]
[Link]
[Link]
[Link] of nodes
[Link]
Enter choice:1
Enter data:123
Node pushed to stack 123
[Link]
[Link]
14
[Link]
[Link] of nodes
[Link]
Enter choice:2
Deleted from Stack 123
[Link]
[Link]
[Link]
[Link] of nodes
[Link]
Enter choice:3
12
123
[Link]
[Link]
[Link]
[Link] of nodes
[Link]
Enter choice:4
Number of nodes 1
[Link]
[Link]
[Link]
[Link] of nodes
[Link]
Enter choice:5
Quit
Result:
Thus the Python program executed successfully.
15
[Link]: 6 IMPLEMENTATION OF QUEUE ADT
Date:17/5/21
Aim:
Write a Python program to the implementation of queue.
Algorithm:
Step1: Start.
Step2:Create a empty queue.
Step3:Append a,b,c to the queue.
Step4:Print initial queue.
Step5:Print the elements dequeued from the queue.
Step6:Pop the element from the index of 0 for twice.
Step7: Print queue after removing the element.
Step8:Stop.
Program:
queue = []
[Link]('a')
[Link]('b')
[Link]('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print([Link](0))
print([Link](0))
print("\nQueue after removing elements")
print(queue)
16
Output:
Initial queue
['a', 'b', 'c']
Elements dequeued from queue
a
b
Queue after removing elements
['c']
Result:
Thus the Python program executed successfully.
17
[Link]: 7 APPLICATION OF LIST(POLYNOMIAL)
Date: 24/5/21
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.
Step 9: Print resultant polynomial.
Step 10: Stop.
Program:
class Node:
def __init__(self):
[Link] = None
[Link] = None
[Link] = None
def addnode(start, coeff, power):
newnode = Node();
[Link] = coeff;
[Link] = power;
[Link] = None;
if (start == None):
return newnode;
ptr = start;
while ([Link] != None):
ptr = [Link];
[Link] = newnode;
return start;
18
def printList(ptr):
while ([Link] != None):
print(str([Link]) + 'x^' + str([Link]), end = '')
if( [Link] != None and [Link] >= 0):
print('+', end = '')
ptr = [Link]
print([Link])
def removeDuplicates(start):
ptr2 = None
dup = None
ptr1 = start;
while (ptr1 != None and [Link] != None):
ptr2 = ptr1;
while ([Link] != None):
if ([Link] == [Link]):
[Link] = [Link] + [Link];
dup = [Link];
[Link] = [Link];
else:
ptr2 = [Link];
ptr1 = [Link];
def multiply(poly1, Npoly2, poly3):
ptr1 = poly1;
ptr2 = poly2;
while (ptr1 != None):
while (ptr2 != None):
coeff = [Link] * [Link];
power = [Link] + [Link];
poly3 = addnode(poly3, coeff, power);
ptr2 = [Link];
ptr2 = poly2;
ptr1 = [Link];
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);
19
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)
Output:
1st Polynomial:- 3x^3+6x^1-9
2nd Polynomial:- 9x^3-8x^2+7x^1+2
Resultant Polynomial:- 27x^6-24x^5+75x^4-123x^3+114x^2-51x^1-18
Result:
Thus the Python program executed successfully.
20
[Link]: 8 IMPLEMENT THE BUBBLESORT
Date: 31/5/21
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)
Step4: For j in range(len(list1)-1)
Step5:Print the unsorted list.
Step 6: Print the sorted list.
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))
21
Output:
The unsorted list is: [5, 3, 8, 6, 7, 2]
The sorted list is: [2, 3, 5, 6, 7, 8]
Result:
Thus the Python program executed successfully.
22
[Link]: 9 IMPLEMENT THE INSERTIONSORT
Date: 31/5/21
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.
Step5:Print the sorted list.
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)
23
Output:
Enter the list of numbers :3 7 1 9 2
Sorted list :[1, 2, 3, 7, 9]
Result:
Thus the Python program executed successfully.
24
Ex.N0: 10 IMPLEMENT THE QUICKSORT
Date: 31/5/21
Aim:
To write a Python program to sort elements using quick sort method.
Algorithm:
Step1:Start.
Step2:Define quick sort.
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:
25
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))
print('Sorted list :',end='')
print(alist)
Output:
Enter the list of numbers :22 7 4 9 1
Sorted list :[1, 4, 7, 9, 22]
Result:
Thus the Python program executed successfully.
26
Ex.N0:11 IMPLEMENT THE BINARY SEARCH
Date: 7/6/21
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!")
return-1
27
lst=[]
size=int(input("Enter size of list :\t"))
for n in range(size):
numbers=int(input("Enter any number :\t"))
[Link](numbers)
[Link]()
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
The list will be sorted,the sorted list is : [2, 8, 22]
Enter the number to be search :22
Entered number 22 is present at position : 2
Result:
Thus the Python program executed successfully.
28
Ex.N0:12 IMPLEMENT THE HASH TABLE
Date:7/6/21
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)
29
Output:
0--> Allahabad
1--> Punjab--> Noida
2
3--> Mathura
4
5--> Mumbai
6
7
8
9--> Delhi
Result:
Thus the Python program executed successfully.
30
Ex.N0:13 IMPLEMENT THE TREE TRAVERSAL
Date: 14/6/21
Aim:
To write a Python program to implement the tree traversal.
Algorithm:
Step1:Start.
Step2:Creating a class as Node.
Step3:Define print Inorder.
Step4:Define print Postorder.
Step 5: Define print Preorder.
Step6:Print preorder traversal of binary tree.
Step7:Print inorder traversal of binary tree.
Step8: Print postorder traversal of binary tree.
Step 9: Stop.
Program:
class Node:
def __init__(self, key):
[Link] = None
[Link] = None
[Link] = key
def printInorder(root):
if root:
printInorder([Link])
print([Link]),
printInorder([Link])
def printPostorder(root):
if root:
printPostorder([Link])
printPostorder([Link])
print([Link]),
def printPreorder(root):
if root:
print([Link]),
printPreorder([Link])
printPreorder([Link])
root = Node(1)
[Link] = Node(2)
31
[Link] = Node(3)
[Link] = Node(4)
[Link] = 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:
Preorder traversal of binary tree is
1
2
4
5
3
Inorder traversal of binary tree is
4
2
5
1
3
Postorder traversal of binary tree is
4
5
2
3
1
Result:
Thus the Python program executed successfully.
32
Ex.N0:14 IMPLEMENT THE BINARY SEARCH TREE
Date:14/6/21
Aim:
To write a Python program to implement the binary search tree.
Algorithm:
Step1:Start.
Step2:Creating a class as BTSNode.
Step3:Define insert function.
Step4:Define inorder.
Step 5: Define replace_node_of_parent.
Step6:Define find_min.
Step7:Define remove function.
Step8: Define search function.
Step 9: Creating a class as BStree.
Step 10: Define inorder.
Step 11: Define add function.
Step 12: Define remove function.
Step 13: Define search function.
Step 14: Creating an object bstree for the class BSTree.
Step 15: Print Menu (this assumes no duplicate keys)
Step 16: Print add <key>.
Step 17: Print remove <key>.
Step 18: Print inorder.
Step 19: Print quit.
Step 20: Get the input from the user to what would you like to do.
Step 21: Print the inorder traversal.
Step 22: Stop.
Program:
class BSTNode:
def __init__(self, key):
[Link] = key
[Link] = None
[Link] = None
[Link] = None
def insert(self, node):
if [Link] > [Link]:
if [Link] is None:
[Link] = node
[Link] = self
33
else:
[Link](node)
elif [Link] < [Link]:
if [Link] is None:
[Link] = node
[Link] = self
else:
[Link](node)
def inorder(self):
if [Link] is not None:
[Link]()
print([Link], end=' ')
if [Link] is not None:
[Link]()
def replace_node_of_parent(self, new_node):
if [Link] is not None:
if new_node is not None:
new_node.parent = [Link]
if [Link] == self:
[Link] = new_node
elif [Link] == self:
[Link] = new_node
else:
[Link] = new_node.key
[Link] = new_node.left
[Link] = new_node.right
if new_node.left is not None:
new_node.[Link] = self
if new_node.right is not None:
new_node.[Link] = self
def find_min(self):
current = self
while [Link] is not None:
current = [Link]
return current
def remove(self):
if ([Link] is not None and [Link] is not None):
successor = [Link].find_min()
[Link] = [Link]
[Link]()
elif [Link] is not None:
self.replace_node_of_parent([Link])
elif [Link] is not None:
self.replace_node_of_parent([Link])
else:
self.replace_node_of_parent(None)
def search(self, key):
if [Link] > key:
if [Link] is not None:
return [Link](key)
else:
34
return None
elif [Link] < key:
if [Link] is not None:
return [Link](key)
else:
return None
return self
class BSTree:
def __init__(self):
[Link] = None
def inorder(self):
if [Link] is not None:
[Link]()
def add(self, key):
new_node = BSTNode(key)
if [Link] is None:
[Link] = new_node
else:
[Link](new_node)
def remove(self, key):
to_remove = [Link](key)
if ([Link] == to_remove
and [Link] is None and [Link] is None):
[Link] = None
else:
to_remove.remove()
def search(self, key):
if [Link] is not None:
return [Link](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])
[Link](key)
elif operation == 'remove':
key = int(do[1])
[Link](key)
elif operation == 'inorder':
print('Inorder traversal: ', end='')
[Link]()
print()
elif operation == 'quit':
break
35
Output:
Menu (this assumes no duplicate keys)
add <key>
remove <key>
inorder
quit
What would you like to do? add 1
What would you like to do? add 5
What would you like to do? add 2
What would you like to do? add 7
What would you like to do? add 3
What would you like to do? inorder
Inorder traversal: 1 2 3 5 7
What would you like to do? remove 7
What would you like to do? add 4
What would you like to do? inorder
Inorder traversal: 1 2 3 4 5
What would you like to do? quit
Result:
Thus the Python program executed successfully.
36
Ex.N0:15 IMPLEMENTATION OF HEAP
Date: 21/6/21
Aim:
To write a Python program to implement the heap.
Algorithm:
Step1:Start.
Step2: Import heapq library.
Step3:Create a list with elements and then heapify.
Step4:Print the created heap.
Step 5: Push the element 4 with the help of heappush.
Step6:Print the modified heap after push.
Step7:Pop the smallest element from the list with the help of heappop.
Step8: Print the popped and smallest element.
Step 9: Stop.
Program:
import heapq
li=[5, 7, 9, 1, 3]
[Link](li)
print("The created heap is : ",end="")
print(list(li))
[Link](li,4)
print("The modified heap after push is : ",end="")
print(list(li))
print("The popped and smallest element is : ",end="")
print([Link](li))
37
Output:
The created heap is : [1, 3, 9, 7, 5]
The modified heap after push is : [1, 3, 4, 7, 5, 9]
The popped and smallest element is : 1
Result:
Thus the Python program executed successfully.
38
Ex.N0:16 IMPLEMENTATION OF GRAPH REPRESENTATION
Date: 21/6/21
Aim:
To write a Python program to implement the graph representation.
Algorithm:
Step1:Start.
Step2:Import default dict.
Step3:Creating a graph with default dict (list).
Step4:Define addEdge.
Step 5: Define generate_edges.
Step6:Create a edge with a empty list.
Step7:For node in graph.
For neighbour in graph [node].
Step8: Append the edge.
Step 9: Print the generated graph.
Step 10: Stop.
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]:
[Link]((node, neighbour))
return edges
addEdge(graph,'a','c')
addEdge(graph,'b','c')
addEdge(graph,'b','e')
addEdge(graph,'c','d')
39
addEdge(graph,'c','e')
addEdge(graph,'c','a')
addEdge(graph,'c','b')
addEdge(graph,'e','b')
addEdge(graph,'d','c')
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:
Thus the Python program executed successfully.
40
Ex.N0:17 IMPLEMENTATION OF SHORTEST PATH ALGORITHM
Date: 28/6/21
Aim:
To write a Python program to implement the shortest path algorithm.
Algorithm:
Step1:Start.
Step2:Creating a class as graph.
Step3:Define print solution.
Step4:Print vertex t distance from source.
Step 5: Define minDistance.
Step6:Define dijkstra.
Step7:Creating an object for the class graph.
Step8: Print.
Step 9: Stop.
Program:
import sys
class Graph():
def __init__(self, vertices):
self.V = vertices
[Link] = [[0 for column in range(vertices)]
for row in range(vertices)]
def printSolution(self, dist):
print("Vertex t Distance from Source")
for node in range(self.V):
print(node, "t", dist[node])
def minDistance(self, dist, sptSet):
min = [Link]
for v in range(self.V):
41
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index
def dijkstra(self, src):
dist = [[Link]] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
u = [Link](dist, sptSet)
sptSet[u] = True
for v in range(self.V):
if [Link][u][v] > 0 and sptSet[v] == False and dist[v] > dist[u] + [Link][u][v]:
dist[v] = dist[u] + [Link][u][v]
[Link](dist)
g = Graph(9)
[Link] = [[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]
]
[Link](0)
42
Output:
Vertex t Distance from Source
0t0
1t4
2 t 12
3 t 19
4 t 21
5 t 11
6t9
7t8
8 t 14
Result:
Thus the Python program executed successfully.
43
Ex.N0:18 IMPLEMENT THE MINIMUM SPANNING TREE ALGORITHM
Date: 5/7/21
Aim:
To write a Python program to implement the minimum spanning tree algorithm.
Algorithm:
Step1:Start.
Step2:Import default dict.
Step3:Creating a class graph.
Step4:Define add edge.
Step 5: Define find function.
Step6:Define union function.
Step7:Define KruskalMST.
Step8: Print the edges in the constructed MST.
Step 9: Creating an object for the class graph.
Step 10: Print the minimum spanning tree.
Step 11: Stop.
Program:
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
[Link] = []
def addEdge(self, u, v, w):
[Link]([u, v, w])
def find(self, parent, i):
if parent[i] == i:
return i
return [Link](parent, parent[i])
def union(self, parent, rank, x, y):
44
xroot = [Link](parent, x)
yroot = [Link](parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def KruskalMST(self):
result = []
i=0
e=0
[Link] = sorted([Link],key=lambda item: item[2])
parent = []
rank = []
for node in range(self.V):
[Link](node)
[Link](0)
while e < self.V - 1:
u, v, w = [Link][i]
i=i+1
x = [Link](parent, u)
y = [Link](parent, v)
if x != y:
e=e+1
[Link]([u, v, w])
[Link](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)
45
g = Graph(4)
[Link](0, 1, 10)
[Link](0, 2, 6)
[Link](0, 3, 5)
[Link](1, 3, 15)
[Link](2, 3, 4)
[Link]()
Output:
Edges in the constructed MST
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Minimum Spanning Tree 19
Result:
Thus the Python program executed successfully.
46