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

0% found this document useful (0 votes)
28 views83 pages

DSA Lab Manual

The document is a lab manual for the Artificial Intelligence and Machine Learning course at Tagore Institute of Engineering and Technology. It contains a list of programming exercises in Python covering data structures and algorithms, including implementations of abstract data types, recursive algorithms, linked lists, stacks, and more. Each program includes an aim, algorithm, code, output, and verification of results.

Uploaded by

HoD CSE TIET
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)
28 views83 pages

DSA Lab Manual

The document is a lab manual for the Artificial Intelligence and Machine Learning course at Tagore Institute of Engineering and Technology. It contains a list of programming exercises in Python covering data structures and algorithms, including implementations of abstract data types, recursive algorithms, linked lists, stacks, and more. Each program includes an aim, algorithm, code, output, and verification of results.

Uploaded by

HoD CSE TIET
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/ 83

TAGORE INSTITUTE OF ENGINEERING AND

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

Department of Computer Science and Engineering


(Artificial Intelligence and Machine Learning)
II Year- III Semester –ARTIFICIAL INTELLIGENCE AND MACHINE
LEARNING

LAB MANUAL
CD3281-DATA STRUCTURES AND ALGORITHIMS LABORATORY

(2021 Regulation)
List of Programs

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


Program No: 1 A
File Name: IMPLEMENTATION OF SIMPLE ABSTRACT
Ex. No: CLASS IN PYTHON
Date: ___________

Aim:

Write a Python program 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. Import the necessary modules.


2. Define the abstract class.
3. Create subclasses that implement the abstract methods.
4. Instantiate the subclasses and use their methods.

Program:

def calculateBill(units):

if (units <= 100):


return units * 10;
elif (units <= 200):
return ((100 * 10) + (units - 100) * 15);
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=int(input("Enter number of units:"))

print(“Payable Amount is : ”)
print(calculateBill(units));
Output:

Enter number of units:320


Payable Amount is :
5000

Result:

Thus the Python program to calculate electricity bill for a given tariff using abstract

class has been implemented and output verified successfully.


Program No: 1 B
File Name: IMPLEMENTATION OF SIMPLE
Ex. No: ABSTRACT CLASS IN PYTHON
Date: ___________

Aim:

To write a Python program for basic operations of calculator.

Algorithm:

1. Import required modules: Start by importing `ABC` and `abstractmethod`


from the `abc` module.
2. Define abstract class: Create an abstract class by inheriting from `ABC`
and use the `@abstractmethod` decorator to declare abstract methods.
3. Create subclasses: Define subclasses that inherit from the abstract class and
implement all the abstract methods.
4. Instantiate subclasses: Create instances of the subclasses to generate
objects.
5. Invoke methods: Call the implemented methods on these objects to
demonstrate their functionality.

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:

Enter first number: 25


Enter second number: 5
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 4
Result: 5.0

0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division

Result:

Thus the Python program for basic operations of calculator using abstract

class has been implemented and output verified successfully.


Program No: 2 A
File Name: IMPLEMENTATION OF SIMPLE RECURSIVE
Ex. No: ALGORITHMS IN PYTHON
Date: ___________ Factorial

Aim:

Write a Python program to find factorial calculation using recursion.

Algorithm:

1. define a function that takes an integer n as input


2. check if n is equal to 0 or 1; if so, return 1
3. if n is greater than 1, return n multiplied by the factorial of n - 1
4. test the function by calling it with various values of n to verify
correctness

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:

def tower_of_hanoi(disks, source, auxiliary, target):

if(disks == 1):

print('Move disk 1 from rod {} to rod {}.'.format(source, target))

return

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

tower_of_hanoi(disks, 'A', 'B', 'C')


Output:

Enter the number of disks: 3


Move disk 1 from rod A to rod C.
Move disk 2 from rod A to rod B.
Move disk 1 from rod C to rod B.
Move disk 3 from rod A to rod C.
Move disk 1 from rod B to rod A.
Move disk 2 from rod B to rod C.
Move disk 1 from rod A to rod C.

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:

To write a Python program to search element in a list using arrays.

Algorithm:

1. define a class to represent the list

2. initialize the class with an array to store elements and a variable to track
the current size

3. implement a method to add an element to the list

4. implement a method to remove an element from the list

5. implement a method to get an element by index

6. implement a method to display the current elements in the list

7. test the class by creating an instance and performing various operations like
adding, removing, and accessing elements

Program:

def SearchByIndex(array_val, index_val) :


item_index= index_val;
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;
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))

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:

///////////////searchByIndex in an Array ////////////////

=========== Original Array =========


Array [ 0 ] 4
Array [ 1 ] 5
Array [ 2 ] 2
Array [ 3 ] 7
Array [ 4 ] 9
Array [ 5 ] 13
Array Item ' 13 ' is in the position 5

///////////////searchByValue in an Array ///////////////

=========== Original Array =========


Array [ 0 ] start
Array [ 1 ] to
Array [ 2 ] study
Array [ 3 ] from
Array [ 4 ] basics
Array Item ' basics ' is in the position 4

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:

To write a Python program to create linked list with n elements.

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

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

Output:

How many elements would you like to add? 5


Enter data item: 10
Enter data item: 20
Enter data item: 30
Enter data item: 40
Enter data item: 50
The linked list: 10 20 30 40 50

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:

To write a Python program to search key element in a linked list.

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:

def ___init__(self, data):


self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def push(self, new_data):


new_node = Node(new_data)
new_node.next = self.head
self.head = new_node

def search(self, x):


current = self.head
while current != None:
if current.data == x:
return True
current = current.next
return False

if __name__ == '__main__':

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

Output:

Enter element to search: 20


Yes

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:

To write a Python program to insert elements into stack.

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)

# Display the queue


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

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

print("After removing an element")


q.display()

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:

To write a Python program for card of game in Python in List ADT

Algorithm:

1. define a class to represent the card game


2. initialize the class with a list to hold the deck of cards
3. implement a method to create and shuffle the deck of cards
4. implement a method to deal a specified number of cards to a player
5. implement a method to display the player's hand of cards
6. implement a method to allow players to play a card from their hand
7. implement a method to check for a winner based on the game's rules
8. test the card game class by simulating a game with multiple players,
dealing cards, and determining the winner

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


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)

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

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:

To write a Python code for infix to postfix conversion

Algorithm:

1. define a function to determine the precedence of operators


2. define a function to convert infix expression to postfix expression using a
stack
3. initialize an empty stack and an output list for the postfix expression
4. iterate through each character in the infix expression:
● if the character is an operand, append it to the output list
● if the character is an operator, pop from the stack to the output
list based on precedence rules
● if the character is a left parenthesis, push it onto the stack
● if the character is a right parenthesis, pop from the stack to the
output list until a left parenthesis is encountered
5. after processing all characters, pop any remaining operators from the stack
to the output list
6. join the output list to form the final postfix expression
7. test the conversion function with various infix expressions to ensure
correctness
Program:

Operators = set(['+', '-', '*', '/', '(', ')', '^']) # collection of Operators
Priority = {'+':1, '-':1, '*':2, '/':2, '^':3} # dictionary having priorities of Operators

def infixToPostfix(expression):

stack = [] # initialization of empty stack


output = ''

for character in expression:


if character not in 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))

Output:

Enter infix expression a+b*c^d-e^f+g*h-i


infix notation: a+b*c^d-e^f+g*h-i
postfix notation: abcd^*+ef^-gh*+i-

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:

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

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)

Output:

FIRST COME FIRST SERVE SCHEDULLING


Enter number of processes : 4
Enter arrival time of process1: 5
Enter burst time of process1: 2
Enter arrival time of process2: 4
Enter burst time of process2: 3
Enter arrival time of process3: 3
Enter burst time of process3: 1
Enter arrival time of process4: 3
Enter burst time of process4: 2
Process | Arrival | Burst | Exit | Turn Around | Wait |
P3 | 3 | 1 | 1 | -2 | -3 |
P4 | 3 | 2 | 3 | 0 | -2 |
P2 | 4 | 3 | 6 | 2 | -1 |
P1 | 5 | 2 | 8 | 3 | 1 |
Average Waiting Time: -1.25

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:

To write a Python script for implementing linear search technique.

Algorithm:

1. define a function that takes a list and a target value as parameters


2. iterate through each element in the list using a loop
3. for each element, check if it matches the target value
4. if a match is found, return the index of the matching element
5. if the loop completes without finding the target, return -1 or a message
indicating the value was not found
6. test the linear search function with various lists and target values to
ensure correctness

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

Write a Python program to search an element in a given linear list using


recursion.

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:

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


if end >= start:
mid = start + (end- start)//2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearchAppr(arr, start, mid-1, x)
else:
return binarySearchAppr(arr, mid+1, end, x)
else:
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")
Output:
Element is present at index 4

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:

1. define a function that takes a list as a parameter


2. determine the length of the list
3. use a nested loop:
● the outer loop runs from the start of the list to the second-to-
last element
● the inner loop runs from the start to the length of the list minus
the current outer loop index
4. compare adjacent elements in the inner loop; if the first element is greater
than the second, swap them
5. repeat the process until no more swaps are needed, indicating the list is
sorted
6. return the sorted list
7. test the bubble sort function with various lists to ensure correctness
Program:

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]

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=" ")
Output:

Sorted array is:

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:

1. define a function that takes a list as a parameter


2. determine the length of the list
3. use a loop to iterate through the list starting from the second element
4. for each element, store it as the current value and set an index for the
position before it
5. use a while loop to compare the current value with elements in the sorted
portion of the list; shift elements to the right if they are greater than the
current value
6. insert the current value into its correct position in the sorted portion of the
list
7. repeat the process for all elements until the list is sorted
8. return the sorted list
9. test the insertion sort function with various lists to ensure correctness

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

arr = [12, 11, 13, 5, 6]


insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])
Output:

Sorted array is:


5
6
11
12
13

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:

1. define a function that takes a list as a parameter


2. determine the length of the list
3. use a loop to iterate over each index from 0 to the second-to-last element:
● set the current index as the minimum index
4. use another loop to find the index of the smallest element in the unsorted
portion of the list:
● compare each element with the current minimum; if a
smaller element is found, update the minimum index
5. swap the smallest found element with the element at the current index
6. repeat the process for all indices until the list is sorted
7. return the sorted list
8. test the selection sort function with various lists to ensure correctness

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]

print ("Sorted array")


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

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:

To write a Python program to print a binary tree in vertical order.

Algorithm:

1. define a class for the hash table


2. initialize an array to store entries
3. implement a hash function to compute an index
4. implement a method to add key-value pairs, handling collisions
5. implement a method to retrieve values by key
6. implement a method to remove key-value pairs
7. implement a method to display the contents of the hash table
8. test the hash table with various operations
Program:

def display_hash(hashTable):
for i in range(len(hashTable)):
print(i, end = " ")

for j in hashTable[i]:
print("-->", end = " ")
print(j, end = " ")
print()

HashTable = [[] for _ in range(10)]


def Hashing(keyvalue):
return keyvalue % len(HashTable)
def insert(Hashtable, keyvalue, value):
hash_key = Hashing(keyvalue)
Hashtable[hash_key].append(value)

insert(HashTable, 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)

Output:

0 --> Allahabad --> Mathura


1 --> Punjab --> Noida
2
3
4
5 --> Mumbai
6
7
8
9 --> Delhi

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:

def __init__(self, data):

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

# Print the Tree


def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()

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

[10, 14, 19, 27, 31, 35, 42]

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:

def __init__(self, data):

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

# Print the Tree


def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()

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

[27, 14, 10, 19, 35, 31, 42]

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:

def __init__(self, data):

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

# Print the Tree


def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()

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

[10, 19, 14, 31, 42, 35, 27]

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

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


inorder(r)

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:

To write a Python program 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 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;

def searchNode(self, temp, value):


#Check whether tree is empty
if(self.root == None):
print("Tree is empty");

else:
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);
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");

Output:

Search for node 5 in the binary tree


Element is present in the binary tree

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:

To write a Python program to find min heap.

Algorithm:

1. define a class for the min heap


2. initialize an empty list to store heap elements
3. implement a method to insert an element:
● add the element to the end of the list
● perform an upward adjustment (heapify up) to maintain the
min heap property
4. implement a method to remove the minimum element:
● swap the root with the last element and remove it
● perform a downward adjustment (heapify down) to restore
the min heap property
5. implement a method to return the minimum element (the root)
6. implement a method to check if the heap is empty
7. test the min heap class by inserting and removing elements to ensure
correctness
Program:

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

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

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

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:

Write a Python program to implement max heap.

Algorithm:

1. define a class for the max heap


2. initialize an empty list for heap elements
3. implement an insert method:
● add the element and heapify up
4. implement a remove method:
● swap the root with the last element, remove it, and heapify down
5. implement a method to return the maximum element (the root)
6. implement a method to check if the heap is empty
7. test the max heap class for correctness

Program:

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

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

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:

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

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:

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

Write a Python program to represent graph using adjacency list.

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:

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

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

Output:

Vertex 0: -> 3 -> 2 -> 1


Vertex 1: -> 2 -> 0
Vertex 2: -> 1 -> 0
Vertex 3: -> 0
Vertex 4:

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:

Write a Python program to traverse a graph using DFS.

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:

# 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


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

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:

Write a Python program to traverse a graph using BFS.

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:

Following is the Breadth-First Search


5 3 7 2 4 8

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:

1. define a function that takes the graph, number of vertices, and


source vertex as parameters
2. initialize a distance list with infinity for all vertices and set the
source distance to zero
3. iterate for all vertices minus one:
- for each edge, update the distance if it can be improved
4. check for negative weight cycles by iterating through all edges
again
5. return the distance list with shortest path lengths
6. test the function with a graph to ensure correctness
Program:

class Graph:
def __init__(self, vertices):
self.M = vertices # Total number of vertices in the graph
self.graph = [] # Array of edges

# Add edges

def add_edge(self, a, b, c):


self.graph.append([a, b, c])

# Print the solution


def print_solution(self, distance):
print("Vertex Distance from Source")
for k in range(self.M):
print("{0}\t\t{1}".format(k, distance[k]))
def bellman_ford(self, src):
distance = [float("Inf")] * self.M
distance[src] = 0
for _ in range(self.M - 1):
for a, b, c in self.graph:
if distance[a] != float("Inf") and distance[a] + c < distance[b]:
distance[b] = distance[a] + c
for a, b, c in self.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)

Output:

Vertex Distance from Source


0 0
1 2
2 4
3 2
4 7

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:

# 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


# 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],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]

g.dijkstra(0)

Output:

Vertex Distance from Source


0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14

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:

# 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

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

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:

1. Input: Graph as a list of edges with weights.


2. Sort all edges in non-decreasing order of their weights.
3. Initialize a disjoint set (union-find) to track connected components.
4. Initialize an empty list for the Minimum Spanning Tree (MST).
5. For each edge in the sorted list:
6. Check if the endpoints belong to different components.
7. If they do:
a. Add the edge to the MST.
b. Union the two components.
8. Stop when the MST contains V−1V - 1V−1 edges.

Program:

from collections import defaultdict

class Graph:

def __init__(self, vertices):


self.V = vertices # No. of vertices
self.graph = [] # default dictionary
# to store 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)
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
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()

Output:

Edges in the constructed MST


2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Minimum Spanning Tree 19

Result:

Thus the Python program to find minimum spanning tree from a given graph
using Kruskal algorithm has been implemented and output verified successfully.

You might also like