DSA Lab Record
DSA Lab Record
S.NO CONTENTS
1 Implement simple ADTs as Python classes
11 Implementation of Heaps
1
Ex. No : 1(a)
Implementation of simple abstract class in Python
Date :
Aim:
Algorithm:
1. Check units consumed is less than equal to the 100, If yes then the total electricity bill will be:
Unit * 10
2. Else if, check that units consumed is less than equal to the 200, if yes then total electricity bill will be:
(100*10)+(units-100)*15
3. Else if, check that units consumed is less than equal to the 300, if yes then total electricity bill will be:
(100*10)+(100*15)+(units-200)*20
4. Else if, check that units consumed greater than 300, if yes then total electricity bill will be:
(100*10)+(100*15)+(100*20)+(units-300)*25
Program:
2
elif (units <= 300):
return 0;
# Driver Code
units = 250;
print(calculateBill(units));
3
Output
Result:
Thus the program for electricity bill preparation has been implemented using class and the output
verified successfully.
4
Ex. No : 1(b)
Implementation of simple abstract class in Python
Date :
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:
5
print("Result: ",round(obj.div(),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
Output
Result:
Thus the program for calculator has been implemented and the output verified successfully.
6
(a) Implementation of simple recursive algorithms- Factorial of a given number
Date :
Aim:
Write a Python program to find factorial calculation using recursion
Algorithm:
1. Start
2. Declare Variable n, fact, i
3. Read number from User
4. Initialize Variable fact=1 and i=1
5. Repeat Until i<=number
5.1 fact=fact*i
5.2 i=i+1
6. Print fact
7. Stop
Program:
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
# recursive call to the function
return (x * factorial(x-1))
# change the value for a different result
num = 7
# to take input from the user
# num = int(input("Enter a number: "))
# call the factorial function
result = factorial(num)
print("The factorial of", num, "is", result)
7
Output
Result:
Thus the program for factorial of a number has been implemented and the output verified successfully.
8
Ex. No : 2(b)
Implementation of simple recursive algorithms in Python
Date :
Algorithm:
Program:
9
Output
Result:
Thus the program for factorial of a number has been implemented and the output verified successfully.
10
Ex. No : 3(a)
Implementation of list using arrays in Python
Date :
Algorithm:
Program:
n = len(array_val);
search_index = 0;
search_value = 'undefined';
while( search_index < n) :
if( search_index == item_index ) :
search_value = array_val[search_index]
break;
search_index = search_index + 1;
return search_value;
def searchByValue(array_val, item) :
n = len(array_val);
search_value = item; # Let's search the index of value 'item'
array_index = 0
search_index= 'undefined';
while( array_index < n ) :
if( array_val[array_index] == search_value ):
search_index = array_index
break;
array_index = array_index + 1;
return search_index;
print("///////////////searchByIndex in an Array ////////////////")
number_array = [4, 5, 2, 7, 9, 13];
print("=========== Original Array =========")
for idex, item in enumerate(number_array):
print("Array Item '", item , "' is in the position ", searchByValue(number_array, 13)) # search by index
11
searchByValue(number_array, 9)
print("///////////////searchByValue in an Array ///////////////")
Output
Result:
Thus the program for list ADT implementation using array has been implemented and the output
verified successfully.
12
Ex. No : 4(a)
Implementation of linked list in Python
Date :
Algorithm:
1. IF PTR = NULL.
2. SET NEW_NODE = PTR.
3. SET PTR = PTR → NEXT.
4. SET NEW_NODE → DATA = VAL.
5. SET NEW_NODE → NEXT = HEAD.
6. SET HEAD = NEW_NODE.
7. EXIT.
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
def display(self):
current = self.head
while current is not None:
print(current.data, end = ' ')
current = current.next
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()
13
Output
Result:
Thus the program for linked list creation with n umber of elements has been implemented and the
output verified successfully.
14
Ex. No : 4(b)
Implementation of linked list in Python
Date :
Algorithm:
Program:
# Node class
class Node:
# Assign data
self.data = data
15
new_node.next = self.head
# Data found
return True
current = current.next
# Driver code
if __name__ == '__main__':
if llist.search(21):
print("Yes")
else:
print("No")
16
Output
Result:
Thus the program for searching key element in a linked list has been implemented and the output
verified successfully.
17
Ex. No : 5(a)
Implementation of Stack in Python
Date :
Algorithm:
1. A pointer called TOP is used to keep track of the top element in the stack.
2. When initializing the stack, we set its value to -1 so that we can check if the stack is empty by comparing TOP
== -1.
3. On pushing an element, we increase the value of TOP and place the new element in the position pointed to
by TOP.
4. On popping an element, we return the element pointed to by TOP and reduce its value.
5. Before pushing, we check if the stack is already full
6. Before popping, we check if the stack is already empty
Program:
# Creating a stack
def create_stack():
stack = []
return stack
return stack.pop()
stack = create_stack()
push(stack, str(1))
push(stack, str(2))
18
push(stack, str(3))
push(stack, str(4))
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))
Output
Result:
Thus the program for implementing stack has been implemented and the output verified successfully.
19
Ex. No : 5(b)
Implementation of Queue in Python
Date :
Algorithm:
Enqueue Operation
Dequeue Operation
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)
20
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
q.display()
q.dequeue()
Output
Result:
Thus the program for implementing queue has been implemented and the output verified successfully.
21
Ex. No : 6(a)
Application of List ADT in Python
Date :
Aim: Write a Python program for card of game in Python in List ADT
Algorithm:
Program:
class Card:
suits = ["spades",
"hearts",
"diamonds",
"clubs"]
values = [None, None,"2", "3",
"4", "5", "6", "7",
"8", "9", "10",
"Jack", "Queen",
"King", "Ace"]
def __init__(self, v, s):
"""suit + value are ints"""
self.value = v
self.suit = s
def __lt__(self, c2):
if self.value < c2.value:
return True
if self.value == c2.value:
if self.suit < c2.suit:
return True
else:
return False
return False
def __gt__(self, c2):
22
if self.value > c2.value:
return True
if self.value == c2.value:
if self.suit > c2.suit:
return True
else:
return False
return False
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 wins(self, winner):
w = "{} wins this round"
w = w.format(winner)
print(w)
def draw(self, p1n, p1c, p2n, p2c):
d = "{} drew {} {} drew {}"
d = d.format(p1n,
p1c,
p2n,
p2c)
print(d)
23
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))
def winner(self, p1, p2):
if p1.wins > p2.wins:
return p1.name
if p1.wins < p2.wins:
return p2.name
return "It was a tie!"
game = Game()
game.play_game()
24
Output
Result:
Thus the program for card of game has been implemented and the output verified successfully.
25
Ex. No : 6(b)
Application of StackADT in Python
Date :
Algorithm:
Program:
Operators = set(['+', '-', '*', '/', '(', ')', '^']) # collection of Operators
Priority = {'+':1, '-':1, '*':2, '/':2, '^':3} # dictionary having priorities of Operators
definfixToPostfix(expression):
26
Output
Result:
Thus the program for infix to postfix conversion has been implemented and the output verified
successfully.
27
Ex. No : 6(c)
Application of Queue ADTin Python
Date :
Aim: Write a Python program for first come first serve scheduling program
Algorithm:
1. Burst Time: In CPU terms, burst time is the amount of time it takes a process to complete its execution.
2. Waiting Time: The total amount of time a process has to wait before executing.
3. Turnaround time: The amount of time it takes after arrival to complete the process. In simple words, it
is the difference between the completion time and the arrival time.
4. Completion Time: The completion time is measured from arrival until the end of the execution.
5. We can calculate different times for various processes with the simple formulas given below:
6. Waiting Time = Turn Around Time - Burst Time.
7. Turnaround time: Burst time + Waiting time
8. Completion time = Total Turnaround Time + Total Arrival Time
Program:
for i in range(n):
key = "P"+str(i+1)
a = int(input("Enter arrival time of process"+str(i+1)+": "))
b = int(input("Enter burst time of process"+str(i+1)+": "))
l = []
l.append(a)
l.append(b)
d[key] = l
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])
28
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)
29
Output
Result:
Thus the program for CPU scheduling algorithm using queue has been implemented and the output
verified successfully.
30
Ex. No : 7(a)
Implementation of Linear Searching Techniques
Date :
Algorithm:
Algorithmlinsrch (a[],x)
{ // a[1:n] is an array of n
elementsindex:= 0;flag:=0;
while(index<n)do
{
if(x = a[index])then
{ flag:=1;break;
}
index++;
}
if(flag=1)
write(“Datafound“);
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)
31
Output
Result:
Thus the program for linear search has been implemented and the output verified successfully.
32
Ex. No : 7(b)
Implementation of Binary Searching Technique
Date :
Aim: Write a Python program to search an element in a give linear list using recursion.
Algorithm
Program:
33
Output
Result:
Thus the program for binary search using recursion has been implemented and the output verified
successfully.
34
Ex. No : 7(c)
Implementation of Sorting Technique
Date :
Aim: Write a Python program to arrange the given elements using bubble sort.
Algorithm:
1. begin BubbleSort(arr)
2. for all array elements
3. if arr[i] > arr[i+1]
4. swap(arr[i], arr[i+1])
5. end if
6. end for
7. return arr
8. end BubbleSort
Program:
def bubbleSort(arr):
n = len(arr)
bubbleSort(arr)
35
Output
Result:
Thus the program for sorting a given element using bubble sort has been implemented and the output
verified successfully.
36
Ex. No : 7(d)
Implementation of Sorting Technique
Date :
Aim: Write a Python program to arrange the given elements using insertion sort.
Algorithm:
Program:
def insertionSort(arr):
key = arr[i]
37
Output
Result:
Thus the program for sorting a given element using insertion sort has been implemented and the output
verified successfully.
38
Ex. No : 7(e)
Implementation of Sorting Technique
Date :
Aim: Write a Python program to arrange the given elements using selection sort.
Algorithm:
Program:
import sys
A = [64, 25, 12, 22, 11]
39
Output
Result:
Thus the program for sorting a given element using selection sort has been implemented and the output
verified successfully.
40
Ex. No : 8
Implementation Hash Table
Date :
Algorithm:
Program:
for i in range(len(hashTable)):
print(i, end = " ")
for j in hashTable[i]:
print("-->", end = " ")
print(j, end = " ")
print()
# Creating Hashtable as
# a nested list.
HashTable = [[] for _ in range(10)]
41
# key for every value.
def Hashing(keyvalue):
return keyvalue % len(HashTable)
hash_key = Hashing(keyvalue)
Hashtable[hash_key].append(value)
# Driver Code
insert(HashTable, 10, 'Allahabad')
insert(HashTable, 25, 'Mumbai')
insert(HashTable, 20, 'Mathura')
insert(HashTable, 9, 'Delhi')
insert(HashTable, 21, 'Punjab')
insert(HashTable, 21, 'Noida')
display_hash (HashTable)
42
Output
Result:
Thus the program for finding collided node using hash tablehas been implemented and the output
verified successfully.
43
Ex. No : 9(a)
Implementation Tree representation and traversal algorithm
Date :
Aim: Write a Python program for inorder traverse to search element from binary tree.
Algorithm:
Program:
classNode:
self.left =None
self.right =None
self.data = data
# Insert Node
def insert(self, data):
ifself.data:
if data <self.data:
ifself.left isNone:
self.left =Node(data)
else:
self.left.insert(data)
elif data >self.data:
ifself.right isNone:
self.right =Node(data)
else:
self.right.insert(data)
else:
self.data = data
44
# 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))
45
Output
Result:
Thus the program for inorder traversal in a binary tree has been implemented and the output verified
successfully.
46
Ex. No : 9(b)
Implementation Tree representation and traversal algorithm
Date :
Aim: Write a Python program for preorder traverse to search element from binary tree.
Algorithm:
Program:
classNode:
self.left =None
self.right =None
self.data = data
# Insert Node
def insert(self, data):
ifself.data:
if data <self.data:
ifself.left isNone:
self.left =Node(data)
else:
self.left.insert(data)
elif data >self.data:
ifself.right isNone:
self.right =Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Preorder traversal
# Root -> Left ->Right
47
defPreorderTraversal(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))
48
Output
Result:
Thus the program for binary tree preorder traversal has been implemented and the output verified
successfully.
49
Ex. No : 9(c)
Implementation Tree representation and traversal algorithm
Date :
Aim: Write a Python program for postorder traversal to search element from binary tree.
Algorithm:
Program:
Program:
classNode:
self.left =None
self.right =None
self.data = data
# Insert Node
def insert(self, data):
ifself.data:
if data <self.data:
ifself.left isNone:
self.left =Node(data)
else:
self.left.insert(data)
elif data >self.data:
ifself.right isNone:
self.right =Node(data)
else:
self.right.insert(data)
else:
self.data = data
50
print(self.data),
ifself.right:
self.right.PrintTree()
# Postorder traversal
# Left ->Right -> Root
defPostorderTraversal(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))
51
Output
Result:
Thus the program for binary tree postorder traversal has been implemented and the output verified
successfully.
52
Ex. No : 10(a)
Implementation Binary Search Tree
Date :
Aim: Write a Python program to insert element into binary tree and display inorder vertical order.
Algorithm:
1. If node == NULL
2. return createNode(data)
3. if (data < node->data)
4. node->left = insert(node->left, data);
5. else if (data > node->data)
6. node->right = insert(node->right, data);
7. return node;
Program:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
53
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)
54
Output
Result:
Thus the program for inserting element in binary tree has been implemented and the output verified
successfully.
55
Ex. No : 10(b)
Implementation Binary Search Tree
Date :
Algorithm:
1. It checks whether the root is null, which means the tree is empty.
2. If the tree is not empty, it will compare temp? ...
3. Traverse left subtree by calling searchNode() recursively and check whether the value is present in left subtree.
Program:
class SearchBinaryTree:
def __init__(self):
#Represent the root of binary tree
self.root = None;
self.flag = False;
#searchNode() will search for the particular node in the binary tree
def searchNode(self, temp, value):
#Check whether tree is empty
if(self.root == None):
print("Tree is empty");
else:
#If value is found in the given binary tree then, set the flag to true
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);
56
bt.root.right = Node(3);
bt.root.left.left = Node(4);
bt.root.right.left = Node(5);
bt.root.right.right = Node(6);
bt.searchNode(bt.root, 5);
if(bt.flag):
print("Element is present in the binary tree");
else:
print("Element is not present in the binary tree");
57
Output
Result:
Thus the program for searching an element in a binary tree has been implemented and the output
verified successfully.
58
Ex. No : 11(a)
Implementation of Heaps
Date :
Algorithm:
1. A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal
to the values in the children of that node.
2. Mapping the elements of a heap into an array is trivial:
if a node is stored at index k, then its left child is stored at index 2k + 1 and
its right child at index 2k + 2 for 0 based indexing and
for 1 based indexing the left child will be at 2k and
right child will be at 2k + 1.
Program:
import sys
class MinHeap:
59
# Function that returns true if the passed
# node is a leaf node
def isLeaf(self, pos):
return pos*2 > self.size
current = self.size
60
# Function to build the min heap using
# the minHeapify function
def minHeap(self):
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__":
minHeap.Print()
print("The Min val is " + str(minHeap.remove()))
61
Output
Result:
Thus the program for min heap has been implemented and the output verified successfully.
62
Ex. No : 11(b)
Implementation of Heaps
Date :
Algorithm:
Program:
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
return 2 * pos
return (2 * pos) + 1
63
# Function that returns true if the passed
# node is a leaf node
def isLeaf(self, pos):
current = self.size
64
self.swap(current, self.parent(current))
current = self.parent(current)
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()
65
Output
Result:
Thus the program max heap implementation has been implemented and the output verified successfully.
66
Ex. No : 12(a)
Graph Representation and Traversal
Date :
Algorithm:
1. An adjacency matrix is a way of representing a graph as a matrix of booleans (0's and 1's).
2. A finite graph can be represented in the form of a square matrix on a computer, where the boolean value of the
matrix indicates if there is a direct path between two vertices.
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
67
for row in self.adjMatrix:
for val in row:
print('{:4}'.format(val)),
print
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()
68
Output
Result:
Thus the program for representing graph using adjacency matrix node has been implemented and the
output verified successfully.
69
Ex. No : 12(b)
Graph Representation and Traversal
Date :
Algorithms:
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
70
if __name__ == "__main__":
V=5
graph.print_agraph()
71
Output
Result:
Thus the program for representing graph using adjacency list node has been implemented and the output
verified successfully.
72
Ex. No : 12(c)
Graph Representation and Traversal
Date :
Algorithms:
1. Create a recursive function that takes the index of the node and a visited array.
2. Mark the current node as visited and print the node.
3. Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the
adjacent node.
Program:
class Graph:
# Constructor
def __init__(self):
73
# recursive DFSUtil()
def DFS(self, v):
# Driver code
74
Output
Result:
Thus the program for DFS traversal and finding path has been implemented and output verified
successfully.
75
Ex. No : 12(d)
Graph Representation and Traversal
Date :
Algorithms:
1. Start by putting any one of the graph’s vertices at the back of the queue.
2. Now take the front item of the queue and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add those which are not within the visited list to the rear of
the queue.
4. Keep continuing steps two and three till the queue is empty.
Program:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
76
Output
Result:
Thus the program for DFS traversal and finding path has been implemented and output verified
successfully.
77
Ex. No : 13(a)
Single Source Shortest Path Algorithm
Date :
Aim:Write a Python program for single source shortest path using Bellman Ford Algorithm.
Algorithms:
1. Initializing the source vertex with distance to itself as 0 and all other vertices as infinity. Creating the
array with size N
2. Calculate the shortest distance from the source vertex. Following this process for N-1 times where N is
the number of vertices in the graph
a. For relaxing the path lengths for the vertices for each edge m-n:
b. if distance[n] > distance[m] + weight of edge mn, then
c. distance[n] = distance[m] + weight of edge mn
3. Even after minimizing the path lengths for each vertex after N-1 times, if we can still relax the path
length where distance[n] > distance[m] + weight of edge mn then we can say that the graph contains the
negative edge cycle.
4. Therefore, the only limitation of the bellman ford algorithm is that it does not work with a graph having
a negative edge cycle.
BELLMAN-FORD (G,w,s)
1 INITIALIZE (G,s)
2 for i ← 1 to |V|-1
3 do for each edge (u,v)∈E
4 do RELAX (u,v,w)
5 for each edge (u,v)∈E
6 do if d[v]>d[u]+w(u,v)
7 then return FALSE
8 return TRUE
Program:
classGraph:
def__init__(self, vertices):
self.M = vertices # Total number of vertices in the graph
self.graph = [] # Array of edges
# Add edges
defadd_edge(self, a, b, c):
self.graph.append([a, b, c])
78
defprint_solution(self, distance):
print("Vertex Distance from Source")
for k inrange(self.M):
print("{0}\t\t{1}".format(k, distance[k]))
defbellman_ford(self, src):
distance = [float("Inf")] *self.M
distance[src] =0
for _ inrange(self.M -1):
for a, b, c inself.graph:
if distance[a] !=float("Inf") and distance[a] + c < distance[b]:
distance[b] = distance[a] + c
for a, b, c inself.graph:
if distance[a] !=float("Inf") and distance[a] + c < distance[b]:
print("Graph contains negative weight cycle")
return
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)
79
Output
Result:
Thus the program for single source shortest pathusing Bellman Ford algorithm has been implemented
and output verified successfully.
80
Ex. No : 13(b)
Single Source Shortest Path Algorithm
Date :
Aim:Write a Python program for single source shortest path using Dijiktra’s Algorithm.
Algorithms:
1. Create a set sptSet (shortest path tree set) that keeps track of vertices included in the shortest-path tree,
i.e., whose minimum distance from the source is calculated and finalized. Initially, this set is empty.
2. Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE.
Assign distance value as 0 for the source vertex so that it is picked first.
Program:
81
# shortest path tree
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index
self.printSolution(dist)
# 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],
82
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
g.dijkstra(0)
83
Output
Result:
Thus the program for single source shortest path using Dijiktra’s algorithm has been implemented and
output verified successfully.
84
Ex. No : 14(a)
Implementation of Minimum Spanning Tree
Date :
Aim:Write a Python program to find minimum spanning tree from a given graph using Prim’s algorithm.
Algorithm:
1. Create a set mstSet that keeps track of vertices already included in MST.
2. Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE. Assign key
value as 0 for the first vertex so that it is picked first.
3. While mstSet doesn’t include all vertices
a. Pick a vertex u which is not there in mstSet and has minimum key value.
b. Include u to mstSet.
c. Update key value of all adjacent vertices of u. To update the key values, iterate through all adjacent
vertices. For every adjacent vertex v, if weight of edge u-v is less than the previous key value of v,
update the key value as weight of u-v
4. The idea of using key values is to pick the minimum weight edge from cut. The key values are used
only for vertices which are not yet included in MST, the key value for these vertices indicate the
minimum weight edges connecting them to the set of vertices included in MST.
Program:
class Graph():
85
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();
86
Output
Result:
Thus the program for finding minimum spanning tree using Prim’s algorithm has been implemented
and output verified successfully.
87
Ex. No : 14(b)
Implementation of Minimum Spanning Tree
Date :
Aim:Write a Python program to find minimum spanning tree from a given graph using Krushkal algorithm.
Algorithm:
Program:
class Graph:
88
yroot = self.find(parent, y)
parent = []
rank = []
89
x = self.find(parent, u)
y = self.find(parent, v)
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()
90
OUTPUT:
Result:
Thus the program for finding minimum spanning tree using Krushkal algorithm has been implemented
and output verified successfully.
91