Lab Manual
Lab Manual
CHENNAI – 600119.
Name :
Reg No :
Batch : 2022-2026
1
JEPPIAAR NAGAR, RAJIVGANDHI SALAI
CHENNAI – 600119.
Date:
Examiners:
Internal:
External:
2
COLLEGE VISION & MISSION
Vision
To build Jeppiaar Engineering College as an Institution of Academic Excellence in Technical
education and Management education and to become a World Class University.
Mission
To equip students with values, ethics and life skills needed to enrich their lives and
M3
enable them to meaningfully contribute to the progress of society
M4 To prepare students for higher studies and lifelong learning, enrich them with the
practical and entrepreneurial skills necessary to excel as future professionals and
contribute to Nation’s economy
3
DEPARTMENT OF INFORMATION TECHNOLOGY
Vision
To produce engineers with excellent knowledge in the field of Information Technology
through scientific and practical education to succeed in an increasingly complex world.
Mission
To demonstrate technical and operational excellence through creative and critical
M1
thinking for the effective use of emerging technologies.
To involve in a constructive, team oriented environment and transfer knowledge to
M2
enable global interaction.
M3 To enrich students with professional integrity and ethical standards that will make
them deal social challenges successfully in their life.
To devise students for higher studies and perpetual learning, upgrade them as
M4
competent engineers and entrepreneurs for country’s development.
Students are able to analyze, design, implement and test any software with the programming
PSO1 and testing skills they have acquired.
Students are able to design algorithms, data management to meet desired needs, for real time
PSO2 problems through analytical, logical and problem solving skills.
Students are able to provide security solutions for network components and data storage &
PSO3 management which will enable them to work in the industry ethically.
Design, implement, and analyse linear data structures, such as lists, queues, and stacks,
C206.2 according to the needs of different applications
C206.3 Design and Implement Hashing techniques.
Design, implement, and analyse efficient tree structures to meet requirements such as
C206.4 searching, indexing, and sorting
4
Model problems as graph problems and implement efficient graph algorithms to solve
C206.5 them
5
LIST OF EXPERIMENTS
6
INDEX PAGE
DATE OF THE DATE OF MARKS SIGNATURE
S.NO NAME OF THE EXPERIMENT Page No
EXPERIMENT SUBMISSION (25) WITH DATE
Implement simple ADTs as Python
1 classes
Implement recursive algorithms in
2 Python
Implement List ADT using Python
3 arrays
Implementation of Singly Linked
4 List
Implementation of Stack using list
5 Implementation of Linear Queue
using list
Applications of List, Stack and
6 Queue ADTs
7a Implementation of Bubble sort
7b Implementation of Insertion Sort
7c Implementation of Selection Sort
7d Implementation of Merge Sort
7e Implementation of Quick Sort
7
Implementation of single source
shortest path algorithm
14
Assessment
Implementation of Singly Linked
List
Implementation of Binary search
Tree representation and traversal
Algorithms
Content Beyond Syllabus
Implementation of minimum spanning tree
15 algorithms- Kruskal’s algorithm
Implementation of minimum spanning tree
16 algorithms-Prim’s algorithm
Program Completion (25)
8
Ex No:1
Date : Implement simple ADTs as Python classes
AIM:
PROGRAM:
class factorial:
def findFact(self, n):
f=1
for i in range(1, n + 1):
f=f*i
return f
ob = factorial()
print("\nFactorial of", num, "=", ob.findFact(num))
OUTPUT :
Enter a Number: 6
Factorial of 6 = 720
RESULT :
9
Ex No:2
Date : Implement recursive algorithms in Python
AIM:
To write the Python program to implement recursive algorithms in
Python
ALGORITHM:
1. Create n variables and initialize them
2. Create another variable to keep track of the length of the Fibonacci
sequence to be printed (length)
3. Loop (length is less than series length)
4. Print first + second
5. Update n variables
PROGRAM:
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms =int(input("Enter the no of terms "))
# check if the number of terms is valid
if n_terms <= 0:
print("Invalid input ! Please input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
OUTPUT:
Enter the no of terms 6
Fibonacci series:
0
1
1
2
3
5
RESULT :
Thus the python program for implementing has been executed and the
output is verified successfully.
10
Ex No:3
Date : Implement List ADT using Python arrays
AIM:
To write the Python program to implement List ADT using Python arrays
ALGORITHM:
Step 1: Creating a List with the use of multiple values
Step 2: Accessing a element from the list using index number
Step 3: Accessing a element
Step 4: Print the last element of list
PROGRAM:
class Student:
def init (self, name, rollno, m1, m2):
self.name = name
self.rollno = rollno
self.m1 = m1
self.m2 = m2
def accept(self, Name, Rollno, marks1, marks2 ):
ob = Student(Name, Rollno, marks1, marks2 )
ls.append(ob)
def display(self, ob):
print("Name : ", ob.name)
print("RollNo : ", ob.rollno)
print("Marks1 : ", ob.m1)
print("Marks2 : ", ob.m2)
print("\n")
def search(self, rn):
for i in range(ls. len ()):
if(ls[i].rollno == rn):
return i
def delete(self, rn):
i = obj.search(rn)
del ls[i]
def update(self, rn, No):
i = obj.search(rn)
roll = No
ls[i].rollno = roll;
ls =[]
obj = Student('', 0, 0, 0)
print("\nOperations used, ")
print("\n1.Accept Student details\n2.Display Student Details\n"
"3.Search Details of a Student\n4.Delete Details of Student"
"\n5.Update Student Details\n6.Exit")
# ch = int(input("Enter choice:"))
# if(ch == 1):
obj.accept("A", 1, 100, 100)
11
obj.accept("B", 2, 90, 90)
obj.accept("C", 3, 80, 80)
# elif(ch == 2):
print("\n")
print("\nList of Students\n")
for i in range(ls. len ()):
obj.display(ls[i])
# elif(ch == 3):
print("\n Student Found, ")
s = obj.search(2)
obj.display(ls[s])
# elif(ch == 4):
obj.delete(2)
print(ls. len ())
print("List after deletion")
for i in range(ls. len ()):
obj.display(ls[i])
# elif(ch == 5):
obj.update(3, 2)
print(ls. len ())
print("List after updation")
for i in range(ls. len ()):
obj.display(ls[i])
# else:
print("")
OUTPUT :
Operations used,
List of Students
Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100
Name : B
RollNo : 2
Marks1 : 90
Marks2 : 90
Name : C
12
RollNo : 3
Marks1 : 80
Marks2 : 80
Student Found,
Name : B
RollNo : 2
Marks1 : 90
Marks2 : 90
2
List after deletion
Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100
Name : C
RollNo : 3
Marks1 : 80
Marks2 : 80
2
List after updation
Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100
Name : C
RollNo : 2
Marks1 : 80
Marks2 : 8
RESULT :
Thus the python program for implementing List ADT using Python
arrays has been executed and the output is verified successfully.
13
Ex No:4
Date : Implementation of Singly Linked List
AIM:
15
OUTPUT :
Item found
Count of nodes is : 6
4
1
6
2
3
5
after removing
4
1
6
3
5
RESULT :
16
Ex No:5(a)
Date : Implementation of Stack using list
AIM:
1. PUSH() Operation:
Step 1: Start
Step 2: Create a node new and declare variable top
Step 3: Set new data part to be Null // The first node is created, having null
value and top pointing to it
Step 4: Read the node to be inserted.
Step 5: Check if the node is Null, then print "Insufficient Memory"
Step 6: If node is not Null, assign the item to data part of new and assign top to
link part of new and also point stack head to new.
2. POP() Operation:
Step 1: Start
Step 2: Check if the top is Null, then print "Stack Underflow."
Step 3: If top is not Null, assign the top's link part to ptr and assign ptr to
stack_head's link part.
Step 4: Stop
3. PEEK() Operation:
Step 1: Start
Step 2: Print or store the node pointed by top variable
Step 3: Stop
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
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:"))
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:
18
print('Quit')
break
19
OUTPUT :
RESULT :
Thus the python program for Implementation of Stack using Linked List
has been executed and the output is verified successfully.
20
Ex No:5(b)
Date : Implementation of Linear Queue using list
AIM:
PROGRAM:
front=0
rear=0
mymax=eval(input("Enter maximum size of queue:"))
21
def createQueue():
queue=[]
return queue
def isEmpty(queue):
return len(queue)==0
def enqueue(queue,item):
queue.append(item)
print("Enqueued to queue",item)
def dequeue(queue):
if isEmpty(queue):
return "Queue is empty"
item=queue[0]
del queue[0]
return item
queue=createQueue()
while True:
print("1.Enqueue")
print("2.Dequeue")
print("3.Display")
print("4.Quit")
ch=int(input("Enter your choice"))
if ch==1:
if rear<mymax:
item=input("Enter any elements:")
enqueue(queue,item)
rear+=1
else:
print("Queue is full")
elif ch==2:
print(dequeue(queue))
elif ch==3:
print(queue)
else:
print("Exit")
break
OUTPUT :
Enter maximum size of queue:5
1.Enqueue
2.Dequeue
3.Display
4.Quit
Enter your choice1
Enter any elements:3
Enqueued to queue 3
22
1.Enqueue
2.Dequeue
3.Display
4.Quit
Enter your choice1
Enter any elements:6
Enqueued to queue 6
1.Enqueue
2.Dequeue
3.Display
4.Quit
Enter your choice2
3
1.Enqueue
2.Dequeue
3.Display
4.Quit
Enter your choice3
['6']
1. Enqueue
2.Dequeue
3.Display
4.Quit
Enter your choice
RESULT :
Thus the python program for implementing Linear Queue using list has
been executed and the output is verified successfully.
23
Ex No:6
Date : Applications of List, Stack and Queue ADTs
AIM:
OUTPUT :
RESULT :
Thus the python program has been executed and the output is verified
successfully.
25
Ex No:7(a)
Date : Implementation of Bubble sort
AIM:
To write the Python program to implement Bubble sort
ALGORITHM:
Step 1: Optimize code, so if the array is already sorted, it doesn't need to go
through the entire process.
Step 2: Traverse through all array elements range (n) also work but outer loop will
Step 3: Repeat one time more than needed
Step 4: Last i elements are already in place
PROGRAM:
def bubble_sort(a):
n = len(a)
for i in range(n):
for j in range(0, n-i-1):
if a[j] > a[j+1] :
a[j], a[j+1] = a[j+1], a[j]
print("Enter elements into list:")
a=[int(x) for x in input().split()]
bubble_sort(a)
print("The sorted list is ",a)
OUTPUT :
Enter elements into list:
47914 2
The sorted list is [1, 2, 4, 7, 9]
RESULT :
Thus the python program for implementing Bubble sort has been
executed and the output is verified successfully.
26
Ex No:7(b)
Date : Implementation of Insertion Sort
AIM:
OUTPUT :
Enter elements into list:
2719
The sorted list is [1, 2, 7, 9]
RESULT :
Thus the python program for implementing Insertion Sort has been
executed and the output is verified successfully.
27
Ex No:7(c)
Date : Implementation of Selection Sort
AIM:
To write the Python program to implement Selection Sort
ALGORITHM:
Step 1: Selection sort in Python
Step 2: Time complexity O(n*n)
Step 3: Sorting by finding min_index
Step 4: Select the minimum element in every iteration
Step 5: Swapping the elements to sort the array
PROGRAM:
arr = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):
arr.append(int(input("Enter the element:")))
print ("The array is:",arr)
for i in range(0,n):
j=i+1
for j in range(j, n):
if arr[i] > arr[j]:
arr[i] ,arr[j] =arr[j] ,arr[i]
print ("Sorted array is:",arr)
OUTPUT :
Enter the Size of the List:5
Enter the element:45
Enter the element:7
Enter the element:28
Enter the element:65
Enter the element:3
The array is: [45, 7, 28, 65, 3]
Sorted array is: [3, 7, 28, 45, 65]
RESULT :
Thus the python program for implementing Selection Sort has been
executed and the output is verified successfully.
28
Ex No:7(d)
Date : Implementation of Merge Sort
AIM:
29
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
arr = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):
arr.append(int(input("Enter the element:")))
print ("The array is:",arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)
OUTPUT :
RESULT :
Thus the python program for implementing Merge Sort has been
executed and the output is verified successfully.
30
Ex No:7(e)
Date : Implementation of Quick Sort
AIM:
To write the Python program to implement Quick Sort
ALGORITHM:
1. Pick an element, called a pivot, from the array.
2. Partitioning: reorder the array so that all elements with values less
than the pivot come before the pivot, while all elements with values
greater than the pivot come after it (equal values can go either way).
After this partitioning, the pivot is in its final position. This is called
the partition operation.
3. Recursively apply the above steps to the sub-array of elements with
smaller values and separately to the sub-array of elements with
greater values.
PROGRAM:
import random
def pivot_place(list1,first,last):
rindex = random.randint(first, last)
list1[rindex], list1[last] = list1[last], list1[rindex]
pivot = list1[last]
left = first
right = last-1
while True:
while left <= right and list1[left] <= pivot:
left = left+1
while left <= right and list1[right] >= pivot:
right = right-1
if right < left:
break
else:
list1[left], list1[right] = list1[right], list1[left]
list1[last], list1[left] = list1[left], list1[last]
return left
def quicksort(list1, first, last):
if first < last:
p=pivot_place(list1, first, last)
quicksort(list1, first, p-1)
quicksort(list1, p+1, last)
list1 = list()
n=int(input("Enter the Size of the List:"))
31
for i in range(n):
list1.append(int(input("Enter the element:")))
print ("The array is:",list1)
quicksort(list1, 0, n-1)
print(list1)
OUTPUT :
Enter the Size of the List:5
Enter the element:45
Enter the element:6
Enter the element:25
Enter the element:64
Enter the element:2
The array is: [45, 6, 25, 64, 2]
The sorted array is: [2, 6, 25, 45, 64]
RESULT :
Thus the python program for implementing quick sort has been
executed and the output is verified successfully.
32
Ex No:8(a)
Date : Implementation of Linear search
AIM:
To write the Python program to implement Linear search
ALGORITHM:
Start from the leftmost element of arr[] and one by one compare x
with each element of arr[]
If x matches with an element, return the index.
If x doesn’t match with any of the elements, return -1.
PROGRAM:
print("Enter the list")
a = [int(x) for x in input().split()]
print (a)
search = int(input("Enter search number"))
for i in range(0,len(a)):
if (search==a[i]):
print(str(search) + " found at position " +str(i))
if(search!=a[i]):
print(" element not found at any position ")
OUTPUT :
586
[5, 8, 6]
Enter search number2
element not found at any position
RESULT :
Thus the python program for Linear search has been executed and the
output is verified successfully.
33
Ex No:8(b)
Date : Implementation of Binary search
AIM:
To write the Python program to implement Binary search
ALGORITHM:
1. Create a function binary_search () which accepts 4 parameters (array,
low, high, a).
2. Then Follow step 3 until the lowest and highest meet each other:
3. mid = (low + high) / 2 if a == arr [mid] return mid ...
4. Intialize the array and the element to be found
5. Print the resulting position if the element is found else print Not
found.
PROGRAM:
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
n=int(input("Enter the Size of the List:"))
arr= [int(x) for x in input().split()]
print ("The array is:",arr)
x=int(input("Enter the element to be search:"))
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
OUTPUT :
Enter the Size of the List:7
1 5 7 8 9 11 12
The array is: [1, 5, 7, 8, 9, 11, 12]
Enter the element to be search:7
Element is present at index 2
RESULT :
Thus the python program for Binary search has been executed and the
output is verified successfully.
34
Ex No:9
Date : Implementation of Hash tables
AIM:
To write the Python program to implement Hash tables
ALGORITHM:
Step 1: Creating Hashtable as a nested list.
Step 2: Hashing Function to return key for every value.
Step 3: Insert Function to add values to the hash table
Step 4: Display_hash
PROGRAM:
class hashTable:
def init (self):
self.size = int(input("Enter the Size of the hash table : "))
self.table = list(0 for i in range(self.size))
self.elementCount = 0
self.comparisons = 0
def isFull(self):
if self.elementCount == self.size:
return True
else:
return False
def hashFunction(self, element):
return element % self.size
def insert(self, element):
# checking if the table is full
if self.isFull():
print("Hash Table Full")
return False
isStored = False
position = self.hashFunction(element)
if self.table[position] == 0:
self.table[position] = element
print("Element " + str(element) + " at position " + str(position))
isStored = True
self.elementCount += 1
else:
print("Collision has occured for element " + str(element) + " at position
" + str(position) + " finding new Position.")
while self.table[position] != 0:
position += 1
if position >= self.size:
position = 0
self.table[position] = element
isStored = True
35
self.elementCount += 1
return isStored
def search(self, element):
found = False
position = self.hashFunction(element)
self.comparisons += 1
if(self.table[position] == element):
return position
isFound = True
else:
temp = position - 1
while position < self.size:
if self.table[position] != element:
position += 1
self.comparisons += 1
else:
return position
position = temp
while position >= 0:
if self.table[position] != element:
position -= 1
self.comparisons += 1
else:
return position
if not found:
print("Element not found")
return False
def remove(self, element):
position = self.search(element)
if position is not False:
self.table[position] = 0
print("Element " + str(element) + " is Deleted")
self.elementCount -= 1
else:
print("Element is not present in the Hash Table")
return
def display(self):
print("\n")
for i in range(self.size):
print(str(i) + " = " + str(self.table[i]))
print("The number of element is the Table are : " + str(self.elementCount))
table1 = hashTable()
table1.insert(50)
table1.insert(100)
table1.insert(76)
table1.insert(85)
36
table1.insert(92)
table1.insert(73)
table1.insert(101)
table1.display()
print()
print("The position of element 92 is : " + str(table1.search(92)))
print("The position of element 85 is : " + str(table1.search(85)))
print("\nTotal number of comaprisons done for searching = " +
str(table1.comparisons))
print()
table1.remove(73)
table1.display()
OUTPUT :
Enter the Size of the hash table : 7
Element 50 at position 1
Element 100 at position 2
Element 76 at position 6
Collision has occured for element 85 at position 1 finding new Position.
Collision has occured for element 92 at position 1 finding new Position.
Collision has occured for element 73 at position 3 finding new Position.
Collision has occured for element 101 at position 3 finding new Position.
0 = 101
1 = 50
2 = 100
3 = 85
4 = 92
5 = 73
6 = 76
The number of element is the Table are : 7
The position of element 92 is : 4
The position of element 85 is : 3
Total number of comaprisons done for searching = 7
Element 73 is Deleted
0 = 101
1 = 50
2 = 100
3 = 85
4 = 92
5=0
6 = 76
The number of element is the Table are : 6
RESULT :
Thus the python program for implementation of Hash tables has been
executed and the output is verified successfully.
37
Ex No:10
Date : Tree representation and traversal algorithms
AIM:
To write the Python program to implement Tree representation algorithm
ALGORITHM:
Step 1: In-order Traversal In this traversal method, the left subtree is
visited first, then the root and later the right sub-tree. ...
Step 2: Pre-order Traversal In this traversal method, the root node is
visited first, then the left subtree and finally the right subtree. ...
Step 3: Post-order Traversal In this traversal method, the root node is
visited last
PROGRAM:
class Node:
def init (self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
def inorderTraversal(self, root):
res = []
if root:
res = self.inorderTraversal(root.left)
res.append(root.data)
res = res + self.inorderTraversal(root.right)
return res
38
def PreorderTraversal(self, root):
res = []
if root:
res.append(root.data)
res = res + self.PreorderTraversal(root.left)
res = res + self.PreorderTraversal(root.right)
return res
def PostorderTraversal(self, root):
res = []
if root:
res = self.PostorderTraversal(root.left)
res = res + self.PostorderTraversal(root.right)
res.append(root.data)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.inorderTraversal(root))
print(root.PreorderTraversal(root))
print(root.PostorderTraversal(root))
OUTPUT :
RESULT :
39
Ex No:11
Date : Implementation of Binary Search Trees
AIM:
To write the Python program to implement of Binary Search Tree
ALGORITHM:
Step 1: We need to create a class (Binary Tree) with instance variable keys, left
and right.
Step 2: Then we define methods set_root, insert_left, insert_right, inorder, and
search.
Step 3: The set_root method will take the key as an argument and set the
variable key equal to it.
Step 4: The insert_left and insert_right methods will insert a node as a left and
right child, respectively.
Step 5: The inorder method displays the inorder traversal.
Step 6: The method search returns a node with a specified key.
Step 7: We need to define the count_nodes function, which will take a binary
tree as an argument.
Step 8: The recursive function count_nodes returns the number of nodes in the
binary tree.
PROGRAM:
class Node:
def init (self, key):
self.key = key
self.left = None
self.right = None
def inorder(root):
if root is not None:
inorder(root.left)
print(str(root.key) + "->", end=' ')
inorder(root.right)
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
else:
node.right = insert(node.right, key)
return node
def minValueNode(node):
current = node
while(current.left is not None):
current = current.left
return current
def deleteNode(root, key):
40
if root is None:
return root
if key < root.key:
root.left = deleteNode(root.left, key)
elif(key > root.key):
root.right = deleteNode(root.right, key)
else:
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
temp = minValueNode(root.right)
root.key = temp.key
root.right = deleteNode(root.right, temp.key)
return root
root = None
root = insert(root, 8)
root = insert(root, 3)
root = insert(root, 1)
root = insert(root, 6)
root = insert(root, 7)
root = insert(root, 10)
root = insert(root, 14)
root = insert(root, 4)
print("Inorder traversal: ", end=' ')
inorder(root)
print("\nDelete 4")
root = deleteNode(root, 4)
print("Inorder traversal: ", end=' ')
inorder(root)
print("\nDelete 6")
root = deleteNode(root, 6)
print("Inorder traversal: ", end=' ')
inorder(root)
print("\nDelete 3")
root = deleteNode(root, 3)
print("Inorder traversal: ", end=' ')
inorder(root)
41
OUTPUT :
Inorder traversal: 1-> 3-> 4-> 6-> 7-> 8-> 10-> 14->
Delete 4
Inorder traversal: 1-> 3-> 6-> 7-> 8-> 10-> 14->
Delete 6
Inorder traversal: 1-> 3-> 7-> 8-> 10-> 14->
Delete 3
Inorder traversal: 1-> 7-> 8-> 10-> 14->
RESULT :
Thus the python program for implementation of Binary Search Tree has
been executed and the output is verified successfully
42
Ex No:12(a)
Date : Implementation of Max Heap
AIM:
To write the Python program to implement MAX HEAP
ALGORITHM:
Step1: The Heap Sort Algorithm in Python, is divided amongst two functions.
Step2: One of them is responsible for creating the heap,
Step3: and the other is responsible for the swapping of elements within the heap
to build a max heap.
Step4: Left child node of a node, multiply the index position by 2 and add 1.
This is shown in the code as 2 * i + 1.
Step5: For the right child node, you do 2 * i + 2.
Step16: The second for loop in it, does something similar, but swaps the root
node with the last value.
PROGRAM:
def heapify(arr, n, i):
largest = i
l=2*i+1
r=2*i+2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr, n, largest)
def insert(array, newNum):
size = len(array)
if size == 0:
array.append(newNum)
else:
array.append(newNum);
for i in range((size//2)-1, -1, -1):
heapify(array, size, i)
def deleteNode(array, num):
size = len(array)
i=0
for i in range(0, size):
if num == array[i]:
break
array[i], array[size-1] = array[size-1], array[i]
array.remove(num)
for i in range((len(array)//2)-1, -1, -1):
heapify(array, len(array), i)
arr = []
insert(arr, 35)
43
insert(arr, 33)
insert(arr, 42)
insert(arr, 10)
insert(arr, 14)
insert(arr, 19)
insert(arr, 27)
insert(arr, 44)
insert(arr, 26)
print ("Max-Heap array: " + str(arr))
deleteNode(arr, 44)
print("After deleting an element: " + str(arr))
deleteNode(arr, 33)
print("After deleting an element: " + str(arr))
OUTPUT :
Max-Heap array: [44, 42, 35, 33, 14, 19, 27, 10, 26]
After deleting an element: [42, 33, 35, 26, 14, 19, 27, 10]
After deleting an element: [42, 26, 35, 10, 14, 19, 27]
RESULT :
Thus the python program for implementation of MAX HEAP has been
executed and the output is verified successfully
44
Date : Implementation of Min Heap
AIM:
PROGRAM:
def min_heapify(A,k):
l = left(k)
r = right(k)
if l < len(A) and A[l] < A[k]:
smallest = l
else:
smallest = k
if r < len(A) and A[r] < A[smallest]:
smallest = r
if smallest != k:
A[k], A[smallest] = A[smallest], A[k]
min_heapify(A, smallest)
def left(k):
return 2 * k + 1
def right(k):
return 2 * k + 2
def build_min_heap(A):
n = int((len(A)//2)-1)
for k in range(n, -1, -1):
min_heapify(A,k)
A = [3,9,2,1,4,5] ,build_min_heap(A) , print(A)
OUTPUT :
Min heap:
[1, 3, 2, 9, 4, 5]
RESULT :
Thus the python program for implementation of Min heap has been
executed and the output is verified successfully.
45
Ex No:13(a)
Date : Graph Representation Using Adjacency List
AIM:
46
graph.add_edge(0, 4)
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(1, 4)
graph.add_edge(2, 3)
graph.add_edge(3, 4)
graph.print_graph()
OUTPUT :
RESULT :
47
Date : Graph Representation Using Adjacency Matrix
AIM:
Adjacency Matrix:
0110
1010
1101
0010
Adjacency Matrix:
010
101
010
RESULT :
49
Ex No:13(c)
Date : Graph Traversal Algorithm Using BFS
AIM:
To write the Python program to implement Graph Traversal Algorithm
Using BFS
ALGORITHM:
Step 1: Start at the root node and push it onto the stack. Check for any adjacent
nodes of the tree and select one node.
Step 2: Raverse the entire branch of the selected node and push all the nodes
into the stack.
Step 3: Upon reaching the end of a branch (no more adjacent nodes) i.e nth leaf
node, move back by a single step and look for adjacent nodes of the n-1th node.
Step 4: If there are adjacent nodes for the n-1th node, traverse those branches
and push nodes onto the stack.
PROGRAM:
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
bfs(visited, graph, 'A')
OUTPUT :
AB C D E F
RESULT :
Thus the python program has been executed and the output is
verified successfully
50
Date : Graph Traversal Algorithm Using DFS
AIM:
OUTPUT :
DFS
AB EI CF JG D H
RESULT :
51
Ex No:14
Date : Implementation of single source shortest path
algorithm
AIM:
To write the Python program to implement single source shortest path
algorithm
ALGORITHM:
1. Create an array d[] to store the shortest distance of all vertex from
the source vertex. Initialize this array by infinity except for d[S] = 0
where S is the source vertex.
2. Create a queue Q and push starting source vertex in it.
while Queue is not empty, do the following for each
edge(u, v) in the graph
If d[v] > d[u] + weight of edge(u, v)
d[v] = d[u] + weight of edge(u, v)
If vertex v is not present in Queue, then push the vertex v
into the Queue.
PROGRAM:
import heapq
def calculate_distances(graph, starting_vertex):
distances = {vertex: float('infinity') for vertex in graph}
distances[starting_vertex] = 0
pq = [(0, starting_vertex)]
while len(pq) > 0:
current_distance, current_vertex = heapq.heappop(pq)
if current_distance > distances[current_vertex]:
continue
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
example_graph = {
'v1': {'v2': 2, 'v4': 1,},
'v2': {'v4': 3, 'v5': 10,},
'v3': {'v1': 4,},
'v4': {'v3': 2, 'v6': 8, 'v7': 4, 'v5': 2},
'v5': {'v7': 6,},
'v6': {'v3': 5,},
'v7': {'v6': 1,},
}
print(calculate_distances(example_graph, 'v1'))
52
OUTPUT :
shortest path
{'v1': 0, 'v2': 2, 'v3': 3, 'v4': 1, 'v5': 3, 'v6': 6, 'v7': 5}
RESULT :
53
Ex No:15(a)
Date : Implementation of minimum spanning tree algorithms
- Kruskal’s algorithm
AIM:
PROGRAM:
class Edge :
OUTPUT :
Edges of minimum spanning tree in graph : [1-2](1) [3-4](2) [1-3](3) [0-1](5)
Cost of minimum spanning tree : 11
RESULT :
Thus the python program for implementation of Kruskal’s algorithm has
been executed and the output is verified successfully
55
Ex No:15(b)
Date : Implementation of minimum spanning tree algorithms
- Prim’s algorithm
AIM:
ALGORITHM:
Step 1 - Remove all loops and parallel edges
Step 2 - Choose any arbitrary node as root node
Step 3 - Check outgoing edges and select the one with less cost
PROGRAM:
INF = 9999999
V=7
G = [[0, 2, 4, 1, 0, 0, 0],
[2, 0, 0, 3, 7, 0, 0],
[4, 0, 0, 2, 0, 5, 0],
[1, 3, 2, 0, 7, 8, 4],
[0, 7, 0, 7, 0, 0, 6],
[0, 0, 5, 8, 0, 0, 1],
[0, 0, 0, 4, 6, 1, 0]]
selected = [0, 0, 0, 0, 0, 0, 0]
no_edge = 0
selected[0] = True
print("Edge : Weight\n")
while (no_edge < V - 1):
minimum = INF
x=0
y=0
for i in range(V):
if selected[i]:
for j in range(V):
if ((not selected[j]) and G[i][j]):
if minimum > G[i][j]:
minimum = G[i][j]
x=i
y=j
print(str(x) + "-" + str(y) + ":" + str(G[x][y]))
selected[y] = True
no_edge += 1
56
OUTPUT :
Edge : Weight
0-3:1
0-1:2
3-2:2
3-6:4
6-5:1
6-4:6
RESULT :
57
59