DSA Lab Manual
DSA Lab Manual
TECHNOLOGY
Deviyakurichi-636112, Thalaivasal (TK), Salem (DT). Website:
www.tagoreiet.ac.in
(Approved by AICTE, New Delhi and Affiliated to Anna University, Chennai)
Accredited by NAAC
LAB MANUAL
CD3281-DATA STRUCTURES AND ALGORITHIMS LABORATORY
(2021 Regulation)
List of Programs
11.Implementation of Heaps
Aim:
Algorithm:
Program:
def calculateBill(units):
# Driver Code
units=int(input("Enter number of units:"))
print(“Payable Amount is : ”)
print(calculateBill(units));
Output:
Result:
Thus the Python program to calculate electricity bill for a given tariff using abstract
Aim:
Algorithm:
Program:
class cal():
def __init__(self,a,b):
self.a=a
self.b=b
def add(self):
return self.a+self.b
def mul(self):
return self.a*self.b
def div(self):
return self.a/self.b
def sub(self):
return self.a-self.b
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
obj=cal(a,b)
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice=int(input("Enter choice: "))
if choice==1:
print("Result: ",obj.add())
elif choice==2:
print("Result: ",obj.sub())
elif choice==3:
print("Result: ",obj.mul())
elif choice==4:
print("Result: ",round(obj.div(),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
Output:
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Result:
Thus the Python program for basic operations of calculator using abstract
Aim:
Algorithm:
Program:
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = int(input("Enter a number: "))
result = factorial(num)
print("The factorial of", num, "is", result)
Output:
Enter a number: 6
The factorial of 6 is 720
Result:
Thus the Python program to find factorial calculation using recursion has been
implemented and output verified successfully.
Program No: 2 B
File Name: IMPLEMENTATION OF SIMPLE RECURSIVE
Ex. No: ALGORITHMS IN PYTHON
Date: ___________
Tower of Hanoi
Aim:
To write a Python program for Tower of Hanoi using recursion.
Algorithm:
1. define a function that takes three parameters: the number of disks, the
source rod, the target rod, and the auxiliary rod
2. check if the number of disks is 1; if so, move the disk from the source rod
to the target rod and print the move
3. if the number of disks is greater than 1, recursively call the function to
move n-1 disks from the source rod to the auxiliary rod
4. move the nth disk from the source rod to the target rod and print the move
5. recursively call the function to move the n-1 disks from the auxiliary rod
to the target rod
6. test the function by calling it with a specific number of disks and
appropriate rod names
Program:
if(disks == 1):
return
Result:
Thus the Python program for Tower of Hanoi using recursion has been
implemented and output verified successfully.
Program No: 3A
File Name: IMPLEMENTATION OF LIST USING
Ex. No:
Date: ___________ ARRAYS IN PYTHON
Aim:
Algorithm:
2. initialize the class with an array to store elements and a variable to track
the current size
7. test the class by creating an instance and performing various operations like
adding, removing, and accessing elements
Program:
searchByValue(number_array, 9)
print("///////////////searchByValue in an Array ///////////////")
Output:
Result:
Thus the Python program to search element in a list using arrays has been
implemented and output verified successfully.
Program No: 4A
File Name: IMPLEMENTATION OF LINKED LIST INPYTHON
Ex. No:
Date: ___________
Aim:
Algorithm:
1. define a class for the node, which includes properties for the data and the
next node
2. define a class for the linked list, which initializes the head of the list
3. implement a method to add a node to the beginning of the list
4. implement a method to add a node to the end of the list
5. implement a method to remove a node by value
6. implement a method to display the elements in the linked list
7. implement a method to search for a node by value
8. test the linked list class by performing various operations like adding,
removing, and displaying nodes
Program:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
Output:
Result:
Thus the Python program to create linked list with n elements has been
implemented and output verified successfully.
Program No: 4B
File Name: IMPLEMENTATION OF LINKED LIST IN
Ex. No: PYTHON
Date: ___________
Aim:
Algorithm:
1. define a class for the node that includes properties for data and a reference
to the next node
2. define a class for the linked list that initializes the head node as None
3. implement a method to add a node at the beginning of the list
4. implement a method to add a node at the end of the list
5. implement a method to remove a node by value
6. implement a method to display all elements in the linked list
7. implement a method to search for a node by value
8. test the linked list class by creating instances and performing operations
like adding, removing, and displaying nodes
Program:
class Node:
class LinkedList:
def __init__(self):
self.head = None
if __name__ == '__main__':
llist = LinkedList()
if llist.search(21):
print("Yes")
else:
print("No")
Output:
Result:
Thus the Python program to search key element in a linked list has been
implemented and output verified successfully.
Program No: 5A
File Name: IMPLEMENTATION OF STACK IN PYTHON
Ex. No:
Date: ___________
Aim:
Algorithm:
1. define a class for the stack that initializes an empty list to store elements
2. implement a method to add an element to the top of the stack (push)
3. implement a method to remove and return the top element from the stack
(pop)
4. implement a method to view the top element without removing it (peek)
5. implement a method to check if the stack is empty
6. implement a method to get the current size of the stack
7. test the stack class by performing various operations like push, pop, peek,
and checking if the stack is empty
Program:
def create_stack():
stack = []
return stack
def check_empty(stack):
return len(stack) == 0
def push(stack, item):
stack.append(item)
print("pushed item: " + item)
def pop(stack):
if (check_empty(stack)):
return "stack is empty"
return stack.pop()
stack = create_stack()
push(stack, str(1))
push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))
Output:
Pushed item: 1
Pushed item: 2
Pushed item: 3
Pushed item: 4
Popped item: 4
Stack after popping an element: [‘1’, ‘2’, ‘3’]
Result:
Thus the Python program to insert elements into stack has been implemented
and output verified successfully.
Program No: 5B
File Name: IMPLEMENTATION OF QUEUE IN PYTHON
Ex. No:
Date: ___________
Aim:
To write a Python program to implement queue.
Algorithm:
1. define a class for the queue that initializes an empty list to store elements
2. implement a method to add an element to the back of the queue (enqueue)
3. implement a method to remove and return the front element from the
queue (dequeue)
4. implement a method to view the front element without removing it (peek)
5. implement a method to check if the queue is empty
6. implement a method to get the current size of the queue
7. test the queue class by performing various operations like enqueue,
dequeue, peek, and checking if the queue is empty
Program:
class Queue:
def __init__(self):
self.queue = []
# Add an element
def enqueue(self, item):
self.queue.append(item)
# Remove an element
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)
def size(self):
return len(self.queue)
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
q.display()
q.dequeue()
Output:
[1, 2, 3, 4, 5]
After removing an element
[2, 3, 4, 5]
Result:
Thus the Python program to implement queue has been implemented and
output verified successfully.
Program No: 6A
File Name: APPLICATION OF LIST ADT IN PYTHON
Ex. No:
Date: ___________ Card Game
Aim:
Algorithm:
Program:
class Card:
suits = ["spades",
"hearts",
"diamonds",
"clubs"]
def __repr__(self):
v = self.values[self.value] +\
" of " + \
self.suits[self.suit]
return v
class Deck:
def __init__(self):
self.cards = []
for i in range(2, 15):
for j in range(4):
self.cards\
.append(Card(i,
j))
shuffle(self.cards)
def rm_card(self):
if len(self.cards) == 0:
Return
return self.cards.pop()
class Player:
def __init__(self, name):
self.wins = 0
self.card = None
self.name = name
class Game:
def __init__(self):
name1 = input("p1 name ")
name2 = input("p2 name ")
self.deck = Deck()
self.p1 = Player(name1)
self.p2 = Player(name2)
def play_game(self):
cards = self.deck.cards
print("beginning War!")
while len(cards) >= 2:
m = "q to quit. Any " + \
"key to play:"
response = input(m)
if response == 'q':
Break
p1c = self.deck.rm_card()
p2c = self.deck.rm_card()
p1n = self.p1.name
p2n = self.p2.name
self.draw(p1n,
p1c,
p2n,
p2c)
if p1c > p2c:
self.p1.wins += 1
self.wins(self.p1.name)
else:
self.p2.wins += 1
self.wins(self.p2.name)
win = self.winner(self.p1,
self.p2)
print("War is over.{} wins"
.format(win))
game = Game()
game.play_game()
Output:
p1 name Raja
p2 name Jeon
beginning War!
q to quit. Any key to play:d
Raja drew 10 of spades Jeon drew Ace of hearts
Jeon wins this round
q to quit. Any key to play:7
Raja drew 4 of diamonds Jeon drew 9 of clubs
Jeon wins this round
q to quit. Any key to play:
Result:
Thus the Python program for card of game in Python in List ADT has been
implemented and output verified successfully.
Program No: 6B
File Name: APPLICATION OF STACK ADT IN PYTHON
Ex. No:
Date: ___________ Infix to Postfix Conversion
Aim:
Algorithm:
Operators = set(['+', '-', '*', '/', '(', ')', '^']) # collection of Operators
Priority = {'+':1, '-':1, '*':2, '/':2, '^':3} # dictionary having priorities of Operators
def infixToPostfix(expression):
Output:
Result:
Thus the Python code for infix to postfix conversion has been implemented
and output verified successfully.
Program No: 6C
File Name: APPLICATION OF QUEUE ADT IN PYTHON
Ex. No:
Date: ___________ first come first serve scheduling
Aim:
To write a Python program for first come first serve scheduling program.
Algorithm:
1. define a class to represent the process with properties for process ID,
arrival time, and burst time
2. define a class for the queue to manage the processes
3. implement a method to add processes to the queue (enqueue)
4. implement a method to process the queue in a first-come, first-served
manner
5. initialize a list to track waiting and turnaround times for each process
6. iterate through the queue, calculating waiting time and turnaround time for
each process
7. display the waiting times and turnaround times for all processes
8. test the scheduling class by creating processes and adding them to the
queue, then processing the queue to show the results
Program:
ET = []
for i in range(len(d)):
# first process
if(i==0):
ET.append(d[i][1][1])
TAT = []
for i in range(len(d)):
TAT.append(ET[i] - d[i][1][0])
WT = []
for i in range(len(d)):
WT.append(TAT[i] - d[i][1][1])
avg_WT = 0
for i in WT:
avg_WT +=i
avg_WT = (avg_WT/n)
Output:
Result:
Thus the Python program for first come first serve scheduling program has
been implemented and output verified successfully.
Program No: 7A
File Name: IMPLEMENTATION OF LINEAR SEARCHING
Ex. No: TECHNIQUES
Date: ___________
Aim:
Algorithm:
Program:
list1 = [1 ,3, 5, 4, 7, 9]
print(list1)
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Output:
[1, 3, 5, 4, 7, 9]
enter the key to search 5
Element found at index: 2
Result:
Thus the Python script for implementing linear search technique program has
been implemented and output verified successfully.
Program No: 7B
File Name: IMPLEMENTATION OF BINARY SEARCHING
Ex. No: TECHNIQUE
Date: ___________
Aim:
Algorithm:
1. define a function that takes a sorted list and a target value as parameters
2. initialize two variables for the start and end indices of the search range
3. use a loop to repeat the search while the start index is less than or equal to
the end index:
● calculate the middle index
● check if the middle element equals the target value; if so, return the
middle index
● if the middle element is less than the target, update the start index to
search the right half
● if the middle element is greater than the target, update the end index
to search the left half
4. if the loop completes without finding the target, return -1 or a message
indicating the value was not found
5. test the binary search function with various sorted lists and target values to
ensure correctness
Program:
Result:
Thus the Python program to search an element in a given linear list using
recursion has been implemented and output verified successfully.
Program No: 7C
File Name: IMPLEMENTATION OF SORTING TECHNIQUE
Ex. No:
Date: ___________ Bubble Sort
Aim:
To write a Python program to arrange the given elements using bubble sort.
Algorithm:
def bubbleSort(arr):
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
11 12 22 25 34 64 90
Result:
Thus the Python program to arrange the given elements using bubble sort has
been implemented and output verified successfully.
Program No: 7D
File Name: IMPLEMENTATION OF SORTING TECHNIQUE
Ex. No:
Date: ___________ Insertion Sort
Aim:
To write a Python program to arrange the given elements using insertion sort.
Algorithm:
Program:
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
Result:
Thus the Python program to arrange the given elements using insertion sort
has been implemented and output verified successfully.
Program No: 7E
File Name: IMPLEMENTATION OF SORTING TECHNIQUE
Ex. No:
Date: ___________ Selection Sort
Aim:
To write a Python program to arrange the given elements using selection sort.
Algorithm:
Program:
import sys
A = [64, 25, 12, 22, 11]
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
Sorted array
11
22
12
25
64
Result:
Thus the Python program to arrange the given elements using selection sort
has been implemented and output verified successfully.
Program No: 8A
File Name: IMPLEMENTATION HASH TABLE
Ex. No:
Date: ___________
Aim:
Algorithm:
def display_hash(hashTable):
for i in range(len(hashTable)):
print(i, end = " ")
for j in hashTable[i]:
print("-->", end = " ")
print(j, end = " ")
print()
display_hash (HashTable)
Output:
Result:
Thus the Python program to print a binary tree in vertical order has been
implemented and output verified successfully.
Program No:9 A
File Name: IMPLEMENTATION TREE REPRESENTATION
Ex. No: AND TRAVERSAL ALGORITHM
Date: ___________
Aim:
To write a Python program for inorder traverse to search element from binary tree.
Algorithm:
1. define a function that takes the root node of the binary tree and the target
value as parameters
2. check if the current node is None; if so, return False
3. recursively call the function to traverse the left subtree
4. check if the current node's value matches the target; if so, return True
5. recursively call the function to traverse the right subtree
6. return the result of the searches in the left and right subtrees
7. test the function with a binary tree and various target values to ensure
correctness
Program:
class Node:
self.left = None
self.right = None
self.data = data
# Insert Node
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
# Inorder traversal
# Left -> Root -> Right
def inorderTraversal(self, root):
res = []
if root:
res = self.inorderTraversal(root.left)
res.append(root.data)
res = res + self.inorderTraversal(root.right)
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))
Output:
Result:
Thus the Python program for inorder traverse to search element from binary
tree has been implemented and output verified successfully.
Program No: 9B
File Name: IMPLEMENTATION TREE REPRESENTATION
Ex. No: AND TRAVERSAL ALGORITHM
Date: ___________
Aim:
To write a Python program for preorder traverse to search element from binary
tree.
Algorithm:
1. define a function that takes the root node of the binary tree and the target
value as parameters
2. check if the current node is None; if so, return False
3. check if the current node's value matches the target; if so, return True
4. recursively call the function to search the left subtree
5. if not found in the left subtree, recursively call the function to search the
right subtree
6. return the result of the searches in the left and right subtrees
7. test the function with a binary tree and various target values to ensure
correctness
Program:
class Node:
self.left = None
self.right = None
self.data = data
# Insert Node
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
# Preorder traversal
# Root -> Left ->Right
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
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.PreorderTraversal(root))
Output:
Result:
Thus the Python program for preorder traverse to search element from binary
tree has been implemented and output verified successfully.
Program No: 9C
File Name: IMPLEMENTATION TREE REPRESENTATION
Ex. No: AND TRAVERSAL ALGORITHM
Date: ___________
Aim:
To write a Python program for postorder traversal to search element from binary
tree.
Algorithm:
1. define a function that takes the root node of the binary tree and the target
value as parameters
2. check if the current node is None; if so, return False
3. recursively call the function to traverse the left subtree
4. recursively call the function to traverse the right subtree
5. check if the current node's value matches the target; if so, return True
6. return the result of the searches in the left and right subtrees
7. test the function with a binary tree and various target values to ensure
correctness
Program:
class Node:
self.left = None
self.right = None
self.data = data
# Insert Node
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
# Postorder traversal
# Left ->Right -> Root
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.PostorderTraversal(root))
Output:
Result:
Thus the Python program for postorder traversal to search element from
binary tree has been implemented and output verified successfully.
Program No: 10A
File Name: IMPLEMENTATION BINARY SEARCH TREE
Ex. No:
Date: ___________
Aim:
To write a Python program to insert element into binary tree and display inorder
vertical order.
Algorithm:
1. define a class for the binary tree node with properties for data, left child,
and right child
2. define a class for the binary tree that initializes the root node
3. implement a method to insert an element into the binary tree:
- if the tree is empty, set the new node as the root
- recursively find the appropriate position based on the value (less than or
greater than the current node)
4. implement a method to display the tree in vertical order:
- use a dictionary to store nodes at each horizontal distance
- perform a modified inorder traversal, updating the horizontal distance as
you traverse
5. sort the dictionary keys and print the nodes in vertical order
6. test the tree by inserting elements and displaying them in vertical order to
ensure correctness
Program:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)
Output:
20
30
40
50
60
70
80
Result:
Thus the Python program to insert element into binary tree and display inorder
vertical order has been implemented and output verified successfully.
Program No: 10B
File Name: IMPLEMENTATION BINARY SEARCH TREE
Ex. No:
Date: ___________
Aim:
Algorithm:
1. define a function that takes the root node of the binary tree and the target
value as parameters
2. check if the current node is None; if so, return False
3. check if the current node's value matches the target; if so, return True
4. recursively call the function to search in the left subtree
5. if not found in the left subtree, recursively call the function to search in the
right subtree
6. return the result of the searches in the left and right subtrees
7. test the function with a binary tree and various target values to ensure
correctness
Program:
class Node:
def __init__(self,data):
#Assign data to the new node, set left and right children to None
self.data = data;
self.left = None;
self.right = None;
class SearchBinaryTree:
def __init__(self):
#Represent the root of binary tree
self.root = None;
self.flag = False;
else:
if(temp.data == value):
self.flag = True;
return;
bt = SearchBinaryTree();
#Add nodes to the binary tree
bt.root = Node(1);
bt.root.left = Node(2);
bt.root.right = Node(3);
bt.root.left.left = Node(4);
bt.root.right.left = Node(5);
bt.root.right.right = Node(6);
if(bt.flag):
print("Element is present in the binary tree");
else:
print("Element is not present in the binary tree");
Output:
Result:
Thus the Python program to search element from binary tree has been
implemented and output verified successfully.
Program No: 11A
File Name: IMPLEMENTATION OF MIN HEAP
Ex. No:
Date: ___________
Aim:
Algorithm:
import sys
class MinHeap:
current = self.size
popped = self.Heap[self.FRONT]
self.Heap[self.FRONT] = self.Heap[self.size]
self.size-= 1
self.minHeapify(self.FRONT)
return popped
# Driver Code
if __name__ == "__main__":
print('The minHeap is ')
minHeap = MinHeap(15)
minHeap.insert(5)
minHeap.insert(3)
minHeap.insert(17)
minHeap.insert(10)
minHeap.insert(84)
minHeap.insert(19)
minHeap.insert(6)
minHeap.insert(22)
minHeap.insert(9)
minHeap.minHeap()
minHeap.Print()
print("The Min val is " + str(minHeap.remove()))
Output:
The minHeap is
PARENT : 3 LEFT CHILD : 5 RIGHT CHILD : 6
PARENT : 5 LEFT CHILD : 9 RIGHT CHILD : 84
PARENT : 6 LEFT CHILD : 19 RIGHT CHILD : 17
PARENT : 9 LEFT CHILD : 22 RIGHT CHILD : 10
The Min val is 3
Result:
Thus the Python program to find min heap has been implemented and output
verified successfully.
Program No: 11B
File Name: IMPLEMENTATION OF MAX HEAP
Ex. No:
Date: ___________
Aim:
Algorithm:
Program:
import sys
class MaxHeap:
self.maxsize = maxsize
self.size = 0
self.Heap = [0] * (self.maxsize + 1)
self.Heap[0] = sys.maxsize
self.FRONT = 1
return pos // 2
# Function to return the position of
# the left child for the node currently
# at pos
def leftChild(self, pos):
return 2 * pos
return (2 * pos) + 1
self.Heap[fpos])
current = self.size
popped = self.Heap[self.FRONT]
self.Heap[self.FRONT] = self.Heap[self.size]
self.size -= 1
self.maxHeapify(self.FRONT)
return popped
# Driver Code
if __name__ == "__main__":
maxHeap = MaxHeap(15)
maxHeap.insert(5)
maxHeap.insert(3)
maxHeap.insert(17)
maxHeap.insert(10)
maxHeap.insert(84)
maxHeap.insert(19)
maxHeap.insert(6)
maxHeap.insert(22)
maxHeap.insert(9)
maxHeap.Print()
Output:
The maxHeap is
PARENT : 84 LEFT CHILD : 22 RIGHT CHILD : 19
PARENT : 22 LEFT CHILD : 17 RIGHT CHILD : 10
PARENT : 19 LEFT CHILD : 5 RIGHT CHILD : 6
PARENT : 17 LEFT CHILD : 3 RIGHT CHILD : 9
The Max val is 84
Result:
Thus the Python program to implement max heap has been implemented and
output verified successfully.
Program No: 12A
File Name: GRAPH REPRESENTATION AND TRAVERSAL
Ex. No:
Date: ___________ Adjacency Matrix representation
Aim:
Algorithm:
1. define a class for the graph node with properties for the node's value and a
list of connected nodes (edges)
2. implement an `__init__` method to initialize the node's value and its edges
list
3. define a class for the graph that initializes an empty list or dictionary to
store nodes
4. implement a method to add a new node to the graph:
● create a new node and append it to the nodes list or dictionary
5. implement a method to add an edge between two nodes:
● update the edges list for both nodes to reflect the connection
6. implement a method to display the graph's nodes and their edges
7. test the graph class by creating nodes, adding edges, and displaying the
graph structure
Program:
class Graph(object):
# Add edges
def add_edge(self, v1, v2):
if v1 == v2:
print("Same vertex %d and %d" % (v1, v2))
self.adjMatrix[v1][v2] = 1
self.adjMatrix[v2][v1] = 1
# Remove edges
def remove_edge(self, v1, v2):
if self.adjMatrix[v1][v2] == 0:
print("No edge between %d and %d" % (v1, v2))
return
self.adjMatrix[v1][v2] = 0
self.adjMatrix[v2][v1] = 0
def __len__(self):
return self.size
def main():
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.print_matrix()
if __name__ == '__main__':
main()
Output:
Result:
Thus the Python program to create and represent nodes in graph has been
implemented and output verified successfully.
Program No: 12B
File Name: GRAPH REPRESENTATION AND TRAVERSAL
Ex. No:
Date: ___________ Adjacency List representation
Aim:
Algorithm:
1. define a class for the graph that initializes an empty dictionary to store
adjacency lists
2. implement a method to add a new vertex:
- check if the vertex already exists; if not, add it to the dictionary with an
empty list
3. implement a method to add an edge between two vertices:
- update the adjacency list for both vertices to reflect the connection
4. implement a method to display the graph:
- iterate through the dictionary and print each vertex with its corresponding
adjacency list
5. test the graph class by adding vertices and edges, then displaying the graph
structure
Program:
class AdjNode:
def __init__(self, value):
self.vertex = value
self.next = None
class Graph:
def __init__(self, num):
self.V = num
self.graph = [None] * self.V
# Add edges
def add_edge(self, s, d):
node = AdjNode(d)
node.next = self.graph[s]
self.graph[s] = node
node = AdjNode(s)
node.next = self.graph[d]
self.graph[d] = node
if __name__ == "__main__":
V=5
graph.print_agraph()
Output:
Result:
Thus the Python program to represent graph using adjacency list in graph has
been implemented and output verified successfully.
Program No: 12C
File Name: DEPTH FIRST TRAVERSAL
Ex. No:
Date: ___________
Aim:
Algorithm:
1. define a function that takes the graph and a starting vertex as parameters
2. initialize an empty set to keep track of visited vertices
3. implement the DFS function:
● mark the current vertex as visited and print or store it
● iterate through the adjacent vertices of the current vertex:
● if an adjacent vertex has not been visited, recursively call the DFS
function on it
4. call the DFS function with the starting vertex
5. test the DFS traversal on a graph to ensure it visits all connected vertices
correctly
Program:
class Graph:
# Constructor
def __init__(self):
# Driver code
Result:
Thus the Python program to traverse a graph using DFS has been implemented
and output verified successfully.
Program No: 12D
File Name: BREADTH FIRSTTRAVERSAL
Ex. No:
Date: ___________
Aim:
Algorithm:
1. define a function that takes the graph and a starting vertex as parameters
2. initialize an empty queue to keep track of vertices to visit
3. initialize an empty set to track visited vertices
4. enqueue the starting vertex and mark it as visited
5. implement a loop that runs while the queue is not empty:
- dequeue a vertex and print or store it
- iterate through the adjacent vertices of the dequeued vertex:
- if an adjacent vertex has not been visited, enqueue it and mark it as
visited
6. test the BFS traversal on a graph to ensure it visits all connected vertices
correctly
Program:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node): #function for BFS
visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
Output:
Result:
Thus the Python program to traverse a graph using BFS has been implemented
and output verified successfully.
Program No: 13A
File Name: SINGLE SOURCE SHORTEST PATH ALGORITHM
Ex. No:
Date: ___________ Bellman Ford Algorithm
Aim:
Write a Python program for single source shortest path using Bellman Ford
Algorithm.
Algorithm:
class Graph:
def __init__(self, vertices):
self.M = vertices # Total number of vertices in the graph
self.graph = [] # Array of edges
# Add edges
self.print_solution(distance)
g = Graph(5)
g.add_edge(0, 1, 2)
g.add_edge(0, 2, 4)
g.add_edge(1, 3, 2)
g.add_edge(2, 4, 3)
g.add_edge(2, 3, 4)
g.add_edge(4, 3, -5)
g.bellman_ford(0)
Output:
Result:
Thus the Python program for single source shortest path using Bellman Ford
Algorithm has been implemented and output verified successfully.
Program No: 13B
File Name: SINGLE SOURCE SHORTEST PATH ALGORITHM
Ex. No:
Date: ___________ Dijiktra’s Algorithm.
Aim:
Write a Python program for single source shortest path using Dijiktra’s
Algorithm.
Algorithm:
1. define a function that takes the graph, number of vertices, and source
vertex as parameters
2. initialize a distance list with infinity and set the source distance to zero
3. create a priority queue and add the source vertex with its distance
4. while the queue is not empty:
● extract the vertex with the minimum distance
● update distances for adjacent vertices if a shorter path is found
5. return the distance list with shortest path lengths
6. test the function with a graph for correctness
Program:
return min_index
# Driver program
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:
Thus the Python program for single source shortest path using Dijiktra’s
Algorithm has been implemented and output verified successfully.
Program No: 14A
File Name: IMPLEMENTATION OF MINIMUM SPANNING TREE
Ex. No:
Date: ___________ Prim’s algorithm
Aim:
Write a Python program to find minimum spanning tree from a given graph using
Prim’s algorithm.
Algorithm:
1. Input: Graph (adjacency matrix or list).
2. Choose a starting vertex.
3. Initialize:
4. MST set (empty).
5. Priority queue (min-heap) for edges.
6. MST edge list (empty).
7. Add edges from the starting vertex to the priority queue.
8. While the MST set does not include all vertices:
9. Extract the minimum weight edge from the priority queue.
10. If the destination vertex is not in the MST set:
● Add the edge to the MST edge list.
● Add the destination vertex to the MST set.
● Add all edges from the new vertex to the priority queue.
11. Output: The edges in the MST edge list.
Program:
class Graph():
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
self.printMST(parent)
g = Graph(5)
g.graph = [ [0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]
g.primMST();
Output:
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
Result:
Thus the Python program to find minimum spanning tree from a given graph
using Prim’s algorithm has been implemented and output verified successfully.
Program No: 14B
File Name: IMPLEMENTATION OF MINIMUM SPANNING TREE
Ex. No:
Date: ___________ Kruskal’salgorithm
Aim:
Write a Python program to find minimum spanning tree from a given graph using
Kruskal algorithm.
Algorithm:
Program:
class Graph:
parent = []
rank = []
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)
# Driver code
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)
# Function call
g.KruskalMST()
Output:
Result:
Thus the Python program to find minimum spanning tree from a given graph
using Kruskal algorithm has been implemented and output verified successfully.