Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views91 pages

DSA Lab Record

The document outlines various programming exercises in Python, focusing on data structures and algorithms, including implementations of ADTs like lists, stacks, and queues, as well as algorithms for sorting, searching, and recursion. Each section provides a specific aim, algorithm, and sample code for practical implementation. The document concludes with successful verification of outputs for each exercise.

Uploaded by

lingamnagaraj133
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views91 pages

DSA Lab Record

The document outlines various programming exercises in Python, focusing on data structures and algorithms, including implementations of ADTs like lists, stacks, and queues, as well as algorithms for sorting, searching, and recursion. Each section provides a specific aim, algorithm, and sample code for practical implementation. The document concludes with successful verification of outputs for each exercise.

Uploaded by

lingamnagaraj133
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

INDEX

S.NO CONTENTS
1 Implement simple ADTs as Python classes

2 Implement recursive algorithms in Python

3 Implement List ADT using Python arrays

4 Linked list implementations of List

5 Implementation of Stack and Queue ADTs

6 Applications of List, Stack and Queue ADTs

7 Implementation of sorting and searching algorithms

8 Implementation of Hash tables

9 Tree representation and traversal algorithms

10 Implementation of Binary Search Trees

11 Implementation of Heaps

12 Graph representation and Traversal algorithms

13 Implementation of single source shortest path algorithm

14 Implementation of minimum spanning tree algorithms

1
Ex. No : 1(a)
Implementation of simple abstract class in Python
Date :

Aim:

WriteaPythonprogram to calculate electricity bill for a given tariff.

• 1 to 100 units – Rs. 10


• 100 to 200 units – Rs. 15
• 200 to 300 units – Rs.20
• above 300 units – Rs. 25

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:

# Python3 implementation to calculate the


# electricity bill

# Function to calculate the


# electricity bill
def calculateBill(units):

# Condition to find the charges


# bar in which the units consumed
# is fall
if (units <= 100):

return units * 10;

elif (units <= 200):

return ((100 * 10) +


(units - 100) * 15);

2
elif (units <= 300):

return ((100 * 10) +


(100 * 15) +
(units - 200) * 20);

elif (units > 300):

return ((100 * 10) +


(100 * 15) +
(100 * 20) +
(units - 300) * 25);

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 :

Aim: Write a Python program for basic operations of calculator

Algorithm:

1. Create a class and using a constructor to initialize values of that class.


2. Create methods for adding, subtracting, multiplying and dividing two numbers and returning the
respective results.
3. Take the two numbers as inputs and create an object for the class passing the two numbers as
parameters to the class.
4. Using the object, call the respective function depending on the choice taken from the user.
5. Print the final result.
6. Exit

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 :

Aim: Write a Python program for Tower of Hanoi using recursion

Algorithm:

1. # Creating a recursive function.


2. def tower_of_hanoi(disks, source, auxiliary, target):
3. if(disks == 1):
4. print('Move disk 1 from rod {} to rod {}.'.format(source, target))
5. return.
6. # function call itself.
7. tower_of_hanoi(disks - 1, source, target, auxiliary)

Program:

# Creating a recursive function


def tower_of_hanoi(disks, source, auxiliary, target):
if(disks == 1):
print('Move disk 1 from rod {} to rod {}.'.format(source, target))
return
# function call itself
tower_of_hanoi(disks - 1, source, target, auxiliary)
print('Move disk {} from rod {} to rod {}.'.format(disks, source, target))
tower_of_hanoi(disks - 1, auxiliary, source, target)

disks = int(input('Enter the number of disks: '))


# We are referring source as A, auxiliary as B, and target as C
tower_of_hanoi(disks, 'A', 'B', 'C') # Calling the function

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 :

Aim: Write a Python program to search element in a list using arrays.

Algorithm:

1. Iterate the array using the loop.


2. Check whether the given key present in the array i.e. arr[i] == key.
3. If yes, print "Search Found".
4. Else.
5. Not Found.

Program:

def SearchByIndex(array_val, index_val) :


item_index= index_val; # search the value belongs to the 'index_val'th position of the

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 [", idex , "] ", item)

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 ///////////////")

string_array = ["start", "to", "study", "from", "basics"];


print("=========== Original Array =========")
for idex, item in enumerate(string_array):
print(" Array [", idex , "] ", item)
print("Array Item '", item ,"' is in the position ", searchByValue(string_array, "basics")) # search by index

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 :

Aim: Write a Python program to create linked list with n elements.

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 append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

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 :

Aim: Write a Python program to search key element in a linked list.

Algorithm:

1. Create a class Node.


2. Create a class LinkedList.
3. Define methods append and display inside the class LinkedList to append data and display the linked
list respectively.
4. Define method find_index to search for the key.

Program:

# Iterative Python program to search


# an element in linked list

# Node class
class Node:

# Function to initialise the


# node object
def __init__(self, data):

# Assign data
self.data = data

# Initialize next as null


self.next = None

# Linked List class


class LinkedList:
def __init__(self):

# Initialize head as None


self.head = None

# This function insert a new node at the


# beginning of the linked list
def push(self, new_data):

# Create a new Node


new_node = Node(new_data)

# 3. Make next of new Node as head

15
new_node.next = self.head

# 4. Move the head to point to new Node


self.head = new_node

# This Function checks whether the value


# x present in the linked list
def search(self, x):

# Initialize current to head


current = self.head

# Loop till current not equal to None


while current != None:
if current.data == x:

# Data found
return True

current = current.next

# Data Not found


return False

# Driver code
if __name__ == '__main__':

# Start with the empty list


llist = LinkedList()

# Use push() to construct list


# 14->21->11->30->10
llist.push(10);
llist.push(30);
llist.push(11);
llist.push(21);
llist.push(14);

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 :

Aim: Write a Python program to insert elements into stack.

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:

# Stack implementation in python

# Creating a stack
def create_stack():
stack = []
return stack

# Creating an empty stack


def check_empty(stack):
return len(stack) == 0

# Adding items into the stack


def push(stack, item):
stack.append(item)
print("pushed item: " + item)

# Removing an element from the stack


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))

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 :

Aim: Write a Python program to implement queue.

Algorithm:

Enqueue Operation

1. check if the queue is full


2. for the first element, set the value of FRONT to 0
3. increase the REAR index by 1
4. add the new element in the position pointed to by REAR

Dequeue Operation

5. check if the queue is empty


6. return the value pointed by FRONT
7. increase the FRONT index by 1
8. for the last element, reset the values of FRONT and REAR to -1

Program:

# Queue implementation in Python

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)

# Display the queue


def display(self):
print(self.queue)

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()

print("After removing an element")


q.display()

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:

1. Get your Classes Ready: There will be three groups in all.


2. Make Your Class Card: The card will contain a value self and suit.
3. Create the Class Deck:
3. Design a Shuffle Method:
4. Make a Draw Card Method:
5. Create Class Players:

Program:

from random import shuffle

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 :

Aim: Write a Python code for infix to postfix conversion

Algorithm:

1. Scanning the expression fromleft to right


2. If the operand is encountered, push it into the stack
3. If the operator is encountered, then pop the corresponding operand fromthe stack and perform
computation
4. Continue the same process and retain the final value in the stack

Program:

Operators = set(['+', '-', '*', '/', '(', ')', '^']) # collection of Operators

Priority = {'+':1, '-':1, '*':2, '/':2, '^':3} # dictionary having priorities of Operators

definfixToPostfix(expression):

stack = [] # initialization of empty stack


output = ''

for character in expression:


if character notin Operators: # if an operand append in postfix expression
output+= character
elif character=='(': # else Operators push onto stack
stack.append('(')
elif character==')':
while stack and stack[-1]!= '(':
output+=stack.pop()
stack.pop()
else:
while stack and stack[-1]!='('and Priority[character]<=Priority[stack[-1]]:
output+=stack.pop()
stack.append(character)
while stack:
output+=stack.pop()
return output

expression = input('Enter infix expression ')


print('infix notation: ',expression)
print('postfix notation: ',infixToPostfix(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:

print("FIRST COME FIRST SERVE SCHEDULLING")


n= int(input("Enter number of processes : "))
d = dict()

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

d = sorted(d.items(), key=lambda item: item[1][0])

ET = []
for i in range(len(d)):
# first process
if(i==0):
ET.append(d[i][1][1])

# get prevET + newBT


else:
ET.append(ET[i-1] + 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)

print("Process | Arrival | Burst | Exit | Turn Around | Wait |")


for i in range(n):
print(" ",d[i][0]," | ",d[i][1][0]," | ",d[i][1][1]," | ",ET[i]," | ",TAT[i]," | ",WT[i]," | ")
print("Average Waiting Time: ",avg_WT)

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 :

Aim: Write a Python script for implementing linear search technique.

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:

def linear_Search(list1, n, key):

# Searching list1 sequentially


for i in range(0, n):
if (list1[i] == key):
return i
return -1

list1 = [1 ,3, 5, 4, 7, 9]

print(list1)

key = int(input("enter the key to search "))

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

1. Compare x with the middle element.


2. If x matches with the middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element.
So we recur for the right half.
4. Else (x is smaller) recur for the left half.

Program:

def binarySearchAppr (arr, start,end, x):


# check condition
ifend>= start:
mid = start +(end- start)//2
# If element is present at the middle
if arr[mid]== x:
return mid
# If element is smaller than mid
elif arr[mid]> x:
return binarySearchAppr(arr, start, mid-1, x)
# Else the element greator than mid
else:
return binarySearchAppr(arr, mid+1,end, x)
else:
# Element is not found in the array
return-1
arr = sorted(['t','u','t','o','r','i','a','l'])
x ='r'
result = binarySearchAppr(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")

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:

# Python program for implementation of Bubble Sort

def bubbleSort(arr):
n = len(arr)

# Traverse through all array elements


for i in range(n-1):
# range(n) also work but outer loop will
# repeat one time more than needed.

# Last i elements are already in place


for j in range(0, n-i-1):

# traverse the array from 0 to n-i-1


# Swap if the element found is greater
# than the next element
if arr[j] > arr[j + 1] :
arr[j], arr[j + 1] = arr[j + 1], arr[j]

# Driver code to test above


arr = [64, 34, 25, 12, 22, 11, 90]

bubbleSort(arr)

print ("Sorted array is:")


for i in range(len(arr)):
print ("% d" % arr[i],end=" ")

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:

1. # creating a function for insertion.


2. def insertion_sort(list1):
3. # Outer loop to traverse through 1 to len(list1)
4. for i in range(1, len(list1)):
5. value = list1[i]
6. # Move elements of list1[0..i-1], that are.
7. # greater than value, to one position ahead.
8. # of their current position.

Program:

# Python program for implementation of Insertion Sort


# Function to do insertion sort

def insertionSort(arr):

# Traverse through 1 to len(arr)


for i in range(1, len(arr)):

key = arr[i]

# Move elements of arr[0..i-1], that are


# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key

# Driver code to test above


arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %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:

1. Set the first element as minimum . Select first element as minimum.


2. Compare minimum with the second element..
3. After each iteration, minimum is placed in the front of the unsorted list.
4. For each iteration, indexing starts from the first unsorted element.

Program:

# Python program for implementation of selection Sort


# Function to do selection sort

import sys
A = [64, 25, 12, 22, 11]

# Traverse through all array elements


for i in range(len(A)):

# Find the minimum element in remaining


# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

# Swap the found minimum element with


# the first element
A[i], A[min_idx] = A[min_idx], A[i]

# Driver code to test above


print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i]),

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 :

Aim: Write a Python program to print a binary tree in vertical order.

Algorithm:

The insertion algorithm is as follows:

1. use hash function to find index for a record


2. If that spot is already in use, we use next available spot in a "higher" index.
3. Treat the hash table as if it is round, if you hit the end of the hash table, go back to the fro nt

The search algorithm is as follows:

1. use hash function to find index of where an item should be.


2. If it isn't there search records that records after that hash location (remember to treat table as cicular)
until either it found, or until an empty record is found. If there is an empty spot in the table before
record is found, it means that the the record is not there.
3. NOTE: it is important not to search the whole array till you get back to the starting index. As soon as
you see an empty spot, your search needs to stop. If you don't, your search will be incredibly slow

The algorithm is as follows:

1. find record and remove it making the spot empty


2. For all records that follow it in the cluster, do the following:
a. determine the hash index of the record
b. determine if empty spot is between current location of record and the hash index.
c. move record to empty spot if it is, the record's location is now the empty spot.

Program:

# Function to display hashtable


def display_hash(hashTable):

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)]

# Hashing Function to return

41
# key for every value.
def Hashing(keyvalue):
return keyvalue % len(HashTable)

# Insert Function to add


# values to the hash table
def insert(Hashtable, keyvalue, value):

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:

1. Step 1: Repeat Steps 2 to 4 while TREE != NULL.


2. Step 2: INORDER(TREE -> LEFT)
3. Step 3: Write TREE -> DATA.
4. Step 4: INORDER(TREE -> RIGHT) [END OF LOOP]
5. Step 5: END.

Program:

classNode:

def __init__(self, data):

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

# Print the Tree


defPrintTree(self):
ifself.left:
self.left.PrintTree()
print(self.data),
ifself.right:
self.right.PrintTree()

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:

1. Return the root node value.


2. Traverse the left subtree by recursively calling the pre-order function.
3. Traverse the right subtree by recursively calling the pre-order function.

Program:

classNode:

def __init__(self, data):

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

# Print the Tree


defPrintTree(self):
ifself.left:
self.left.PrintTree()
print(self.data),
ifself.right:
self.right.PrintTree()

# 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:

1. Step 1: Repeat Steps 2 to 4 while TREE != NULL.


2. Step 2: POSTORDER(TREE -> LEFT)
3. Step 3: POSTORDER(TREE -> RIGHT)
4. Step 4: Write TREE -> DATA.
5. [END OF LOOP]
6. Step 5: END.

Program:

Program:

classNode:

def __init__(self, data):

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

# Print the Tree


defPrintTree(self):
ifself.left:
self.left.PrintTree()

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:

# Python program to demonstrate


# insert operation in binary search tree

# A utility class that represents


# an individual node in a BST

class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key

# A utility function to insert


# a new node with the given key

def insert(root, key):


if root is None:
return Node(key)
else:
if root.val == key:
return root
elif root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return root

# A utility function to do inorder tree traversal

53
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)

# Driver program to test the above functions


# Let us create the following BST
# 50
#/ \
# 30 70
#/\/\
# 20 40 60 80

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)

# Print inoder traversal of the BST


Ino33999rder(r)

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 :

Aim: Write a Python program to search element from binary tree.

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:

#Represent a node of binary tree


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;

#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;

#Search in left subtree


if(self.flag == False and temp.left != None):
self.searchNode(temp.left, value);

#Search in right subtree


if(self.flag == False and temp.right != None):
self.searchNode(temp.right, value);

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);

print("Search for node 5 in the binary tree")

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 :

Aim: Write a Python program to find min heap.

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:

# Python3 implementation of Min Heap

import sys

class MinHeap:

def __init__(self, maxsize):


self.maxsize = maxsize
self.size = 0
self.Heap = [0]*(self.maxsize + 1)
self.Heap[0] = -1 * sys.maxsize
self.FRONT = 1

# Function to return the position of


# parent for the node currently
# at pos
def parent(self, pos):
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

# Function to return the position of


# the right child for the node currently
# at pos
def rightChild(self, pos):
return (2 * pos) + 1

59
# Function that returns true if the passed
# node is a leaf node
def isLeaf(self, pos):
return pos*2 > self.size

# Function to swap two nodes of the heap


def swap(self, fpos, spos):
self.Heap[fpos], self.Heap[spos] = self.Heap[spos], self.Heap[fpos]

# Function to heapify the node at pos


def minHeapify(self, pos):

# If the node is a non-leaf node and greater


# than any of its child
if not self.isLeaf(pos):
if (self.Heap[pos] > self.Heap[self.leftChild(pos)] or
self.Heap[pos] > self.Heap[self.rightChild(pos)]):

# Swap with the left child and heapify


# the left child
if self.Heap[self.leftChild(pos)] < self.Heap[self.rightChild(pos)]:
self.swap(pos, self.leftChild(pos))
self.minHeapify(self.leftChild(pos))

# Swap with the right child and heapify


# the right child
else:
self.swap(pos, self.rightChild(pos))
self.minHeapify(self.rightChild(pos))

# Function to insert a node into the heap


def insert(self, element):
if self.size >= self.maxsize :
return
self.size+= 1
self.Heap[self.size] = element

current = self.size

while self.Heap[current] < self.Heap[self.parent(current)]:


self.swap(current, self.parent(current))
current = self.parent(current)

# Function to print the contents of the heap


def Print(self):
for i in range(1, (self.size//2)+1):
print(" PARENT : "+ str(self.Heap[i])+" LEFT CHILD : "+
str(self.Heap[2 * i])+" RIGHT CHILD : "+
str(self.Heap[2 * i + 1]))

60
# Function to build the min heap using
# the minHeapify function
def minHeap(self):

for pos in range(self.size//2, 0, -1):


self.minHeapify(pos)

# Function to remove and return the minimum


# element from the heap
def remove(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__":

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()))

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 :

Aim: Write a Python program to implement max heap.

Algorithm:

1. Remove root node.


2. Move the last element of last level to root.
3. Compare the value of this child node with its parent.
4. If value of parent is less than child, then swap them.

Program:

# Python3 implementation of Max Heap


import sys

class MaxHeap:

def __init__(self, maxsize):

self.maxsize = maxsize
self.size = 0
self.Heap = [0] * (self.maxsize + 1)
self.Heap[0] = sys.maxsize
self.FRONT = 1

# Function to return the position of


# parent for the node currently
# at pos
def parent(self, pos):

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

# Function to return the position of


# the right child for the node currently
# at pos
def rightChild(self, pos):

return (2 * pos) + 1

63
# Function that returns true if the passed
# node is a leaf node
def isLeaf(self, pos):

if pos >= (self.size//2) and pos <= self.size:


return True
return False

# Function to swap two nodes of the heap


def swap(self, fpos, spos):

self.Heap[fpos], self.Heap[spos] = (self.Heap[spos],


self.Heap[fpos])

# Function to heapify the node at pos


def maxHeapify(self, pos):

# If the node is a non-leaf node and smaller


# than any of its child
if not self.isLeaf(pos):
if (self.Heap[pos] < self.Heap[self.leftChild(pos)] or
self.Heap[pos] < self.Heap[self.rightChild(pos)]):

# Swap with the left child and heapify


# the left child
if (self.Heap[self.leftChild(pos)] >
self.Heap[self.rightChild(pos)]):
self.swap(pos, self.leftChild(pos))
self.maxHeapify(self.leftChild(pos))

# Swap with the right child and heapify


# the right child
else:
self.swap(pos, self.rightChild(pos))
self.maxHeapify(self.rightChild(pos))

# Function to insert a node into the heap


def insert(self, element):

if self.size >= self.maxsize:


return
self.size += 1
self.Heap[self.size] = element

current = self.size

while (self.Heap[current] >


self.Heap[self.parent(current)]):

64
self.swap(current, self.parent(current))
current = self.parent(current)

# Function to print the contents of the heap


def Print(self):

for i in range(1, (self.size // 2) + 1):


print(" PARENT : " + str(self.Heap[i]) +
" LEFT CHILD : " + str(self.Heap[2 * i]) +
" RIGHT CHILD : " + str(self.Heap[2 * i + 1]))

# Function to remove and return the maximum


# element from the heap
def extractMax(self):

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__":

print('The maxHeap is ')

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()

print("The Max val is " + str(maxHeap.extractMax()))

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 :

Aim: Write a Python program to create and represent nodes in graph.

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:

# Adjacency Matrix representation in Python

class Graph(object):

# Initialize the matrix


def __init__(self, size):
self.adjMatrix = []
for i in range(size):
self.adjMatrix.append([0 for i in range(size)])
self.size = size

# 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

# Print the matrix


def print_matrix(self):

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 :

Aim:Write a Python program to represent graph using adjacency list.

Algorithms:

1. An adjacency list represents a graph as an array of linked lists.


2. The index of the array represents a vertex.
3. Each element in its linked list represents the other vertices that form an edge with the vertex.

Program:

# Adjascency List representation in Python

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

# Print the graph


def print_agraph(self):
for i in range(self.V):
print("Vertex " + str(i) + ":", end="")
temp = self.graph[i]
while temp:
print(" -> {}".format(temp.vertex), end="")
temp = temp.next
print(" \n")

70
if __name__ == "__main__":
V=5

# Create graph and edges


graph = Graph(V)
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(0, 3)
graph.add_edge(1, 2)

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 :

Aim:Write a Python program to traverse a graph using DFS.

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:

# Python3 program to print DFS traversal


# from a given graph
from collections import defaultdict

# This class represents a directed graph using


# adjacency list representation

class Graph:

# Constructor
def __init__(self):

# default dictionary to store graph


self.graph = defaultdict(list)

# function to add an edge to graph


def addEdge(self, u, v):
self.graph[u].append(v)

# A function used by DFS


def DFSUtil(self, v, visited):

# Mark the current node as visited


# and print it
visited.add(v)
print(v, end=' ')

# Recur for all the vertices


# adjacent to this vertex
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)

# The function to do DFS traversal. It uses

73
# recursive DFSUtil()
def DFS(self, v):

# Create a set to store visited vertices


visited = set()

# Call the recursive helper function


# to print DFS traversal
self.DFSUtil(v, visited)

# Driver code

# Create a graph given


# in the above diagram
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)

print("Following is DFS from (starting from vertex 2)")


g.DFS(2)

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 :

Aim:Write a Python program to traverse a graph using BFS.

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' : []
}

visited = [] # List for visited nodes.


queue = [] #Initialize a queue

defbfs(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 notin visited:
visited.append(neighbour)
queue.append(neighbour)

# 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])

# Print the solution

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.

3. While sptSet doesn’t include all vertices


a. Pick a vertex u which is not there in sptSet and has a minimum distance value.
b. Include u to sptSet.
c. Update distance value of all adjacent vertices of u. To update the distance values, iterate through all
adjacent vertices. For every adjacent vertex v, if the sum of distance value of u (from source) and
weight of edge u-v, is less than the distance value of v, then update the distance value of v.

Program:

# Python program for Dijkstra's single


# source shortest path algorithm. The program is
# for adjacency matrix representation of the graph
class Graph():

def __init__(self, vertices):


self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]

def printSolution(self, dist):


print("Vertex \t Distance from Source")
for node in range(self.V):
print(node, "\t\t", dist[node])

# A utility function to find the vertex with


# minimum distance value, from the set of vertices
# not yet included in shortest path tree
def minDistance(self, dist, sptSet):

# Initialize minimum distance for next node


min = 1e7

# Search not nearest vertex not in the

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

# Function that implements Dijkstra's single source


# shortest path algorithm for a graph represented
# using adjacency matrix representation
def dijkstra(self, src):

dist = [1e7] * self.V


dist[src] = 0
sptSet = [False] * self.V

for cout in range(self.V):

# Pick the minimum distance vertex from


# the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minDistance(dist, sptSet)

# Put the minimum distance vertex in the


# shortest path tree
sptSet[u] = True

# Update dist value of the adjacent vertices


# of the picked vertex only if the current
# distance is greater than new distance and
# the vertex in not in the shortest path tree
for v in range(self.V):
if (self.graph[u][v] > 0 and
sptSet[v] == False and
dist[v] > dist[u] + self.graph[u][v]):
dist[v] = dist[u] + self.graph[u][v]

self.printSolution(dist)

# 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:

# A Python program for Prim's Minimum Spanning Tree (MST) algorithm.


# The program is for adjacency matrix representation of the graph

import sys # Library for INT_MAX

class Graph():

def __init__(self, vertices):


self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]

# A utility function to print the constructed MST stored in parent[]


def printMST(self, parent):
print ("Edge \tWeight")
for i in range(1, self.V):
print (parent[i], "-", i, "\t", self.graph[i][parent[i]])

# A utility function to find the vertex with


# minimum distance value, from the set of vertices
# not yet included in shortest path tree
def minKey(self, key, mstSet):

# Initialize min value


min = sys.maxsize

85
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v

return min_index

# Function to construct and print MST for a graph


# represented using adjacency matrix representation
def primMST(self):

# Key values used to pick minimum weight edge in cut


key = [sys.maxsize] * self.V
parent = [None] * self.V # Array to store constructed MST
# Make key 0 so that this vertex is picked as first vertex
key[0] = 0
mstSet = [False] * self.V

parent[0] = -1 # First node is always the root of

for cout in range(self.V):

# Pick the minimum distance vertex from


# the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minKey(key, mstSet)

# Put the minimum distance vertex in


# the shortest path tree
mstSet[u] = True

# Update dist value of the adjacent vertices


# of the picked vertex only if the current
# distance is greater than new distance and
# the vertex in not in the shortest path tree
for v in range(self.V):

# graph[u][v] is non zero only for adjacent vertices of m


# mstSet[v] is false for vertices not yet included in MST
# Update the key only if graph[u][v] is smaller than key[v]
if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]:
key[v] = self.graph[u][v]
parent[v] = u

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:

1. Sort all the edges in non-decreasing order of their weight.


2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not
formed, include this edge. Else, discard it.
3. Repeat step#2 until there are (V-1) edges in the spanning tree.

Program:

# Python program for Kruskal's algorithm to find


# Minimum Spanning Tree of a given connected,
# undirected and weighted graph

from collections import defaultdict

# Class to represent a graph

class Graph:

def __init__(self, vertices):


self.V = vertices # No. of vertices
self.graph = [] # default dictionary
# to store graph

# function to add an edge to graph


def addEdge(self, u, v, w):
self.graph.append([u, v, w])

# A utility function to find set of an element i


# (uses path compression technique)
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])

# A function that does union of two sets of x and y


# (uses union by rank)
def union(self, parent, rank, x, y):
xroot = self.find(parent, x)

88
yroot = self.find(parent, y)

# Attach smaller rank tree under root of


# high rank tree (Union by Rank)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot

# If ranks are same, then make one as root


# and increment its rank by one
else:
parent[yroot] = xroot
rank[xroot] += 1

# The main function to construct MST using Kruskal's


# algorithm
def KruskalMST(self):

result = [] # This will store the resultant MST

# An index variable, used for sorted edges


i=0

# An index variable, used for result[]


e=0

# Step 1: Sort all the edges in


# non-decreasing order of their
# weight. If we are not allowed to change the
# given graph, we can create a copy of graph
self.graph = sorted(self.graph,
key=lambda item: item[2])

parent = []
rank = []

# Create V subsets with single elements


for node in range(self.V):
parent.append(node)
rank.append(0)

# Number of edges to be taken is equal to V-1


while e < self.V - 1:

# Step 2: Pick the smallest edge and increment


# the index for next iteration
u, v, w = self.graph[i]
i=i+1

89
x = self.find(parent, u)
y = self.find(parent, v)

# If including this edge doesn't


# cause cycle, include it in result
# and increment the indexof result
# for next edge
if x != y:
e=e+1
result.append([u, v, w])
self.union(parent, rank, x, y)
# Else discard the edge

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

You might also like