0% found this document useful (0 votes)
11 views64 pages

New Data Structures Design Lab Manual

The document is a lab manual for Data Structures Design at Anna University, detailing various experiments and implementations in Python. It includes sections on Abstract Data Types (ADTs), recursive algorithms, linked lists, stacks, and queues, with step-by-step algorithms and sample code for each. The manual serves as a practical guide for students to execute and understand fundamental data structure concepts.

Uploaded by

anitha
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)
11 views64 pages

New Data Structures Design Lab Manual

The document is a lab manual for Data Structures Design at Anna University, detailing various experiments and implementations in Python. It includes sections on Abstract Data Types (ADTs), recursive algorithms, linked lists, stacks, and queues, with step-by-step algorithms and sample code for each. The manual serves as a practical guide for students to execute and understand fundamental data structure concepts.

Uploaded by

anitha
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/ 64

lOMoARcPSD|50370378

New Data Structures Design lab Manual

Data structures design (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Anitha A ([email protected])
lOMoARcPSD|50370378

JANSONS INSTITUTE OF TECHNOLOGY


Approved by AICTE & Affiliated to Anna University
An ISO 9001:2015 Certified Institution
KARUMATHAMPATTI, COIMBATORE-641659.

LABORATORY RECORD

NAME OF THE STUDENT :

REGISTER NO :

YEAR /SEMESTER :

NAME OF THE LAB

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

JANSONS INSTITUTE OF TECHNOLOGY


KARUMATHAMPATTI, COIMBATORE-641659.

DEPARTMENT:

This is to certify that this ____

________________________________________________(Lab Name) record work done by

Mr/Ms._____________________________________________________________________ for

the course B.E./B.Tech __________________________________________________

(Branch) during _____________ (Year/Semester) of Academic year 2022-2023 is bonafide.

In-Charge Head of the Department

Register No. ________________________________________

The record is submitted for ___________________(Year/Semester) B.E./ B.Tech Practical


Examination of Anna University conducted on______________________.

Internal Examiner External Examiner

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

TABLE OF CONTENTS
Sl. Page
Date Name of the Experiment Sign
No No
1 Implement simple ADTs as Python class

2 Implement recursive algorithms in Python


Implement List ADT using Python arrays
3

Linked list implementations of List


4

Implementation of Stack ADT’s using List


5A

Implementation of Queue ADT’s using List


5B

Implementation of Stack Application: Infix to Postfix


6A

Implementation of Queue Application: Print Queue in


6B Windows

Implementation of List Application: Print Student Details


6C with Mark

Implementation of sorting algorithms


7A

Implementation of searching algorithms


7B

Implementation of Hash tables


8

Tree representation and traversal algorithms


9

Implementation of Binary Search Trees


10
Implementation of Heaps
11
Graph representation and Traversal algorithms
12
Implementation of single source shortest path algorithm
13
Implementation of minimum spanning tree algorithms
14
Implementation of AVL Tree
15

i
Downloaded by Anitha A ([email protected])
lOMoARcPSD|50370378

Ex. No: 01
Implement Simple ADT’s as Python
Date: Class

AIM:
To write a Python program to perform simple ADT’s.
ALGORITHM:
STEP 1: Start the program
STEP 2: Create array and read the values.
STEP 3: Print the result.
STEP 4: Create the list x1 and x2.
STEP 5: Read the values.
STEP 6: Print the result.
STEP 7: Assign new value for x2[1].
STEP 8: Print the result.
STEP 9: Create stack.
STEP 10: Perform insert and delete operation using append and pop method.
STEP 11: Display the result.
STEP 12: Create queue.
STEP 13: Perform insert and delete operation using append and pop method.
STEP 14: Display the result.
STEP 15: Create graph.
STEP 16: Use looing statement to compute vertices and edges and Perform insert operation
using append method.
STEP 17: Display the result.
STEP 18: Stop the program.

PROGRAM:
1.1 ARRAY ADT
import array as arr
a = arr.array("I",[3,6,9])
type(a)

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

print(a)
OUTPUT:
array('I', [3, 6, 9])

1.2 LIST ADT


x1 = [1,2,3]
x2 = list([1,'apple',3])
print(x1)
print(x2[1])
x2[1] = 'orange'
print(x2)

OUTPUT:
[1, 2, 3]
Apple
[1, 'orange', 3]

1.3 STACK ADT


stack = [1,2,3,4,5]
stack.append(6)
print(stack)
stack.pop()
stack.pop()
print(stack)

OUTPUT:

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4]
1.4 QUEUE ADT
queue = [1,2,3,4,5]
queue.append(6)
print(queue)
queue.pop(0)

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

queue.pop(0)
print(queue)

OUTPUT:

[1, 2, 3, 4, 5, 6]
[3, 4, 5, 6]

RESULT:
The python program to create simple ADT’s was successfully executed.

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No: 02
Implement recursive algorithms in Python
Date:

AIM:
To write a Python program to perform recursive function.

ALGORITHM:
STEP 1: Start the program
STEP 2: Read the value of num.
STEP 3: Check IF x==1 means return 1.
STEP 4: Otherwise use recursive function (x * factorial(x-1)).
STEP 5: Print the result.
STEP 6: Stop the program.

PROGRAM:
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))

OUTPUT:
The factorial of 3 is 6

RESULT:
The python program to find factorial of a number using recursive function was successfully
executed.

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No: 03
Implement List ADT using Python arrays
Date:

AIM:
To write a Python program for List ADT’s using array.

ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class.
STEP 3: Create an empty array inside the init function.
STEP 4: Create an object for that class
STEP 5: Do various list operation like insert, delete, append etc.
STEP 6: Print the result.
STEP 7: Stop the program.
PROGRAM:
class List:
def __init__self():
self.elements = []
self.slices = []

def insert(self, data):


self.elements.append(data)
return data

def delete(self):
return self.elements.pop()

definsertpos(self,pos,num):
size=(len(self.elements))
print (size)
if(pos<0):
print("invalid pos")
self.elements.insert(pos,num)
print(self.elements)

def deletepos(self,posdel):
return self.elements.pop(posdel)

def slice(self,start,end):
slices=self.elements[start:end]
5

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

print(slices)

def last(self):
return self.elements[-1]

def first(self):
return self.elements[0]

def is_empty(self):
return len(self.elements) == 0
list = List()
#adding the elements
list.insert(1)
list.insert(2)
list.insert(3)
list.insert(4)
list.insert(5)
print ("The elements in the list:",list.elements)
print("The first elements in the list:",list.first())
print("The last in the list:",list.last())
print("Check whether the list is empty or not:",list.is_empty())
#removing the element -> 1
pos=int(input("enter the position to insert an element"))
num=int(input("enter a number"))
list.insertpos(pos,num)
list.delete()
print ("The elements in the list after delete:",list.elements)
posdel=int(input("enter the position to delete"))
list.deletepos(posdel)
print ("The elements in the list:",list.elements)
start=int(input("enter the starting index value"))
end=int(input("enter the end index value"))
list.slice(start,end)

OUTPUT:
The elements in the list: [1, 2, 3, 4, 5]
The first elements in the list: 1
The last in the list: 5
Check whether the list is empty or not: False
enter the position to insert an element 3
enter a number 7
[1, 2, 3, 7, 4, 5]
The elements in the list after delete: [1, 2, 3, 7, 4]

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

enter the position to delete2


The elements in the list: [1, 2, 7, 4]
enter the starting index value 2
enter the end index value 3
[7]

RESULT:
The python program for creating list was successfully executed.

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No: 04
Linked list implementations of List
Date:

AIM:
To write a Python program for Linked list implementation of list.

ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class.
STEP 3: Create a node with contain both data and next field.
STEP 4: Do various linked list operation like insert, delete and display.
STEP 6: Print the result.
STEP 7: Stop the program.
PROGRAM:
4.1 INSERTION
class Node:
def __init__(self, dataval=None):
self.dataval = datival
self.nextval = None

class SLinkedList:
def _ _ init__(self):
self.headval = None

#function to add newnode


def AtBegining(self,newdata):
NewNode = Node(newdata)
# Update the new nodes next val to existing node
NewNode.nextval = self.headval
self.headval = NewNode

# Function to add newnode


def AtEnd(self, newdata):
NewNode = Node(newdata)
if self.headval is None:
self.headval = NewNode
return
laste = self.headval
while(laste.nextval):

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

laste = laste.nextval
laste.nextval=NewNode

# Function to add node


def Inbetween(self,middle_node,newdata):
if middle_node is None:
print("The mentioned node is absent")
return
NewNode = Node(newdata)
NewNode.nextval = middle_node.nextval
middle_node.nextval = NewNode

# Print the linked list


def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval

list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Thu")
list.headval.nextval = e2
e2.nextval = e3
list.AtBegining("Sun")
list.Inbetween(list.headval.nextval,"Fri")
list.AtEnd("Thu")
list.listprint()

OUTPUT
Sun
Mon
Fri
Tue
Thu
Thu
9

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

4.2 DELETE
class Node:
def _ _ init__ (self, data=None):
self.data = data
self.next = None

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

def Atbegining(self, data_in):


NewNode = Node(data_in)
NewNode.next = self.head
self.head = NewNode
# Function to remove node
def RemoveNode(self, Removekey):
HeadVal = self.head
if (HeadVal is not None):
if (HeadVal.data == Removekey):
self.head = HeadVal.next
HeadVal = None
return
while (HeadVal is not None):
if HeadVal.data == Removekey:
break
prev = HeadVal
HeadVal = HeadVal.next
if (HeadVal == None):
return
prev.next = HeadVal.next
HeadVal = None

def LListprint(self):
printval = self.head
while (printval):
print(printval.data)
printval = printval.next

llist = SLinkedList()
llist.Atbegining("Mon")
llist.Atbegining("Tue")
llist.Atbegining("Wed")
llist.Atbegining("Thu")
llist.RemoveNode("Tue")
llist.LListprint()

10

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

OUTPUT:
Thu
Wed
Mon

RESULT:
The python program for creating linked list was successfully executed.

11

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No: 5A
Implementation of Stack ADT’S using List
Date:

AIM:
To write a Python program for stack implementation using list.

ALGORITHM:

STEP 1: Start the program


STEP 2: Create a class.
STEP 3: Do various stack operation like push, pop and display.
STEP 4: Print the result.
STEP 5: Stop the program.

PROGRAM:

class Stack:
def _ _ init__ (self):
self.elements = []

def push(self, data):


self.elements.append(data)
return data

def pop(self):
return self.elements.pop()

def peek(self):
return self.elements[-1]

def is_empty(self):
return len(self.elements) == 0

stack = Stack()
## checking is_empty method -> true
print("Whether the stack is empty-->",stack.is_empty())
#pushing the elements
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
print("The elements in the stack is:",stack.elements)
#again checking is_empty method -> false
print("Whether the stack is empty-->",stack.is_empty())

12

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

#printing the topmost element of the stack -> 5


print("The topmost element in the stack:",stack.peek())
#popping the topmost element -> 5
print("pop",stack.pop()
#checking the topmost element using peek method -> 4
print("The topmost element in the stack:",stack.peek())
# popping all the elements
stack.pop()
stack.pop()
stack.pop()
stack.pop()
#checking the is_empty method for the last time -> true
print("Whether the stack is empty-->",stack.is_empty())

OUTPUT:
Whether the stack is empty--> True
The elements in the stack is: [1, 2, 3, 4,
5] Whether the stack is empty--> False
The topmost element in the stack: 5 pop 5

The topmost element in the stack:


4 Whether the stack is empty-->
True

RESULT:
The python program for creating a stack ADT was successfully executed.

13

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No: 5B
Implementation of Queue ADT’S using List
Date:

AIM:
To write a Python program for Queue implementation using list.

ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class.
STEP 3: Do various queue operation like insert, delete and display.
STEP 4: Print the result.
STEP 5: Stop the program.
PROGRAM:
class Queue:
def _ _ init__ (self):
self.elements = []
def enqueue(self, data):
self.elements.append(data)
return data
def rear(self):
return self.elements[-1]
def front(self):
return self.elements[0]
def is_empty(self):
return len(self.elements) == 0
def dequeue(self):
return self.elements.pop(0)
queue = Queue()
#adding the elements
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
queue.enqueue(5)
print ("The elements in the
queue:",queue.elements) print("The elements in
the rear is:",queue.rear()) print("The elements in
the front is:",queue.front())
print("Check whether the queue is empty or not:",queue.is_empty())
#removing the element -> 1
queue.dequeue()
queue.dequeue()
print ("The elements in the queue:",queue.elements)

14

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

OUTPUT:
The elements in the queue: [1, 2, 3, 4, 5]
The elements in the rear is: 5
The elements in the front is: 1
Check whether the queue is empty or not:
False

The elements in the queue: [3, 4, 5]

RESULT:
The python program for creating a queue ADT was successfully executed.

15

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No: 6 A Implementation of Stack Application: Infix


Date: to Postfix

AIM:
To write a Python program for Stack Application.

ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class.
STEP 3: Do various operations.
STEP 4: Print the result.
STEP 5: Stop the program.

PROGRAM:

# set of operators
OPERATORS = set(['+', '-', '*', '/', '(', ')', '^'])
# dictionary having priorities
PRIORITY = {'+':1, '-':1, '*':2, '/':2, '^':3}
def infix_to_postfix(expression): #input expression
stack = [] # initially stack empty
output = ‘’ # initially output empty
for ch in expression:
if ch not in OPERATORS: # if an operand then put it directly in postfix expression
output+= ch
elif ch=='(': # else operators should be put in stack
stack.append('(')
elif ch==')':
while stack and stack[-1]!= '(':
output+=stack.pop()
stack.pop()
else:
# lesser priority can't be on top on higher or equal priority
# so pop and put in output
while stack and stack[-1]!='(' and PRIORITY[ch]<=PRIORITY[stack[-1]]:
output+=stack.pop()
stack.append(ch)
while stack:
output+=stack.pop()
return output
expression = input('Enter infix expression')
print('infix expression: ',expression)

16

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

print('postfix expression: ',infix_to_postfix(expression))

OUTPUT:
Enter infix expressiona+b*c
infix expression: a+b*c
postfix expression: abc*+

RESULT:
The python program for creating a Stack application was successfully executed.

17

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No: 6 B Implementation of Queue Application: Print


Date: Queue in Windows

AIM:
To write a Python program for Queue application.

ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class.
STEP 3: Do various operations.
STEP 4: Print the result.
STEP 5: Stop the program.
PROGRAM:
class Queue:
def __init__(self,max_size):
self.__max_size=max_size
self.__elements=[None]*self.__max_size
self.__rear=-1
self.__front=0

def is_full(self):
if(self.__rear==self. __max_size-1):
return True
return False

def is_empty(self):
if(self.__front>self.__rear):
return True
return False

def enqueue(self,data):
if(self.is_full()):
print("Queue is full!!!")
else:
self.__rear+=1
self.__elements[self.__rear]=data
def dequeue(self):
if(self.is_empty()):
print("Queue is empty!!!")
else:
data=self.__elements[self.__front]
self.__front+=1
return data

18

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

def display(self):
for index in range(self.__front, self.__rear+1):
print(self.__elements[index])

def get_max_size(self):
return self.__max_size

#You can use the below __str__() to print the elements of the DS object while
#debugging

def __str__(self):
msg=[]
index=self.__front
while(index<=self.__rear):
msg.append((str)(self.__elements[index]))
index+=1
msg=" ".join(msg)
msg="Queue data(Front to Rear): "+msg
return msg

#function that enqueue are the documents to be printed in Queue named print_queue
def send_for_print(doc):
global print_queue
if(print_queue.is_full()):
print("Queue is full")
else:
print_queue.enqueue(doc)
print(doc,"sent for printing")

#function that prints the document if number of pages of document is less than
#total number of pages in printer
def start_printing():
global print_queue
while(not print_queue.is_empty()):
#here we dequeue the Queue and take the coument that was input first for printing.
doc=print_queue.dequeue()
global pages_in_printer
#the aim of this for loop is to find number of pages of the of document which is doc
name #followed by “-“
for i in range(0,len(doc)):
if(doc[i]=="-"):
no_of_pages=int(doc[i+1:])
break
if(no_of_pages<=pages_in_printer):
print(doc,"printed")
pages_in_printer-=no_of_pages
print("Remaining no. of pages in printer:", pages_in_printer)
else:
print("Couldn't print",doc[:i],". Not enough pages in the printer.")
pages_in_printer=12
print_queue=Queue(10)
send_for_print("doc1-5")
19

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

send_for_print("doc2-3")
send_for_print("doc3-6")
start_printing()

OUTPUT:
doc1-5 sent for printing
doc2-3 sent for printing
doc3-6 sent for printing
doc1-5 printed
Remaining no. of pages in printer: 7
doc2-3 printed
Remaining no. of pages in printer: 4
Couldn't print doc3 . Not enough pages in the printer.

RESULT:
The python program for creating a Queue application was successfully executed.

20

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No:6 C Implementation of List Application: Print


Date: Student Details with Mark

AIM:
To write a Python program for List application.

ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class.
STEP 3: Do various operations.
STEP 4: Print the result.
STEP 5: Stop the program.
PROGRAM:

class students:
count = 0
def init(self, name):
self.name = name
self.marks = []
students.count = students.count + 1

def enterMarks(self):
for i in range(3):
m = int(input("Enter the marks of %s in %d subject: "%(self.name, i+1)))
self.marks.append(m)

def display(self):
print(self.name, "got ", self.marks)

name = input("Enter the name of Student:")


s1 = students(name)
s1.enterMarks()
s1.display()
print ("")
name = input("Enter the name of Student:")
s2 = students(name)
s2.enterMarks()
s2.display()
s2.displayCount()

21

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

OUTPUT:
Enter the name of Student:RAMA
Enter the marks of RAMA in 1 subject: 60
Enter the marks of RAMA in 2 subject: 70
Enter the marks of RAMA in 3 subject: 80
RAMA got [60, 70, 80]

RESULT:
The python program for creating a List application was successfully executed.

22

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No:7A
Implementation of sorting algorithms
Date:

AIM:
To write a Python program for various sorting algorithms.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Bubble Sort:

 Starting with the first element(index = 0), compare the current element with the next
element of the array.
 If the current element is greater than the next element of the array, swap them.
 If the current element is less than the next element, move to the next element
STEP 3: Insertion Sort:
 If it is the first element, it is already sorted.
 Pick the next element.
 Compare with all the elements in sorted sub-list.
 Shift all the elements in sorted sub-list that is greater than the value to be sorted.
 Insert the value.
 Repeat until list is sorted
STEP 4: Selection Sort:
 Get a list of unsorted numbers
 Set a marker for the unsorted section at the front of the list
 Repeat STEPs 4 - 6 until one number remains in the unsorted section
 Compare all unsorted numbers in order to select the smallest one
 Swap this number with the first number in the unsorted section
 Advance the marker to the right one position
STEP 5: Quick Sort:
 Choose the highest index value has pivot
 Take two variables to point left and right of the list excluding pivot left points to the low
index

23

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

 right points to the high


 while value at left is less than pivot move right
 while value at right is greater than pivot move left
 if both STEP 5 and STEP 6 does not match swap left and right
 if left ≥ right, the point where they met is new pivot
STEP 6: Merge Sort:
 If it is only one element in the list it is already sorted, return.
 Divide the list recursively into two halves until it can no more be divided.
 Merge the smaller lists into new list in sorted order.
STEP 7: Stop the program.

PROGRAM:
7a.1. BUBBLE SORT
def b_sort(a):
n = len(a)
for i in range(n):
for j in range(0, n-i-1):
if a[j] > a[j+1] :
a[j], a[j+1] = a[j+1], a[j]
print("Enter elements into list:")
a=[int(x) for x in input().split()]
b_sort(a)
print("The sorted list is ",a)

OUTPUT:

24

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

7a.2 INSERTION SORT


def i_sort(a):
for i in range(1,len(a)):
temp=a[i]
pos=i
while pos>0 and a[pos-1]>temp:
a[pos]=a[pos-1] pos-=1
a[pos]=temp
print("Enter elements into list:")
a=[int(x) for x in input().split()]
i_sort(a)
print("The sorted list is",a)

OUTPUT:

7a.3. SELECTION SORT

def s_sort(a):
for i in range(len(a)):
least=i
for k in range(i+1,len(a)):
if a[k]<a[least]:
least=k swap(a,least,i)

def swap(a,least,i):
temp=a[least]
a[least]=a[i]
a[i]=temp

25

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

print("Enter elements into list:")


a=[int(x) for x in input().split()]
s_sort(a)
print("The sorted list is",a)

OUTPUT:

7a.4 QUICK SORT:


def q_sort(a,low,high):
if low<high:
pivotpos=partition(a,low,high)
q_sort(a,low,pivotpos-1)
q_sort(a,pivotpos+1,high)

def partition(a,low,high):
pivotvalue=a[low]
up=low+1
down=high
done=False
while not done:
while up<=down and a[up]<=pivotvalue:
up+=1
while down>=up and a[down]>=pivotvalue:
down-=1
if down<up:
done=True
else:

26

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

temp=a[up]
a[up]=a[down]
a[down]=temp
temp=a[low]
a[low]=a[down]
a[down]=temp
return down

print("Enter elements into list:")


a=[int(x) for x in input().split()]
high=len(a)
q_sort(a,0,high-1)
print("The sorted list is",a)

OUTPUT:

7a.5 MERGE SORT:

def m_sort(a):
for i in range(len(a)):
if i>1:
mid=len(a)//2
l_half=a[:mid]
r_half=a[mid:]
m_sort(l_half)
m_sort(r_half)
i=j=k=0
while i<len(l_half) and j<len(r_half):
if l_half[i]<r_half[j]:
27

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

a[k]=l_half[i] i+=1
else:
a[k]=r_half[j] j+=1
k+=1

while i<len(l_half):
a[k]=l_half[i]
i+=1
k+=1

while j<len(r_half):
a[k]=r_half[j]
j+=1
k+=1

print("Enter elements into list:")


a=[int(x) for x in input().split()]
m_sort(a)
print("The sorted list is",a)

OUTPUT:

RESULT:
The python program for creating a sorting algorithms was successfully execute.

28

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No: 7B
Implementation of searching algorithms
Date:

AIM:
To write a Python program for various searching algorithms.
ALGORITHM:

STEP 1: Start the program.


STEP 2: Linear Search
STEP 1: Select the first element as the current element.
STEP 2: Compare the current element with the target element. If matches, then go to
STEP 5.
STEP 3: If there is a next element, then set current element to next element and go to
STEP 2.
STEP 4: Target element not found. Stop the Program.
STEP 5: Target element found and return location.
STEP 3: Binary Search:
STEP 1: Find middle element of the array.
STEP 2: Compare the value of the middle element with the target value.
STEP 3: If they match, it is returned.
STEP 4: If the value is less or greater than the target, the search continues in the lower
or upper half of the array accordingly.
STEP 5: The same procedure as in STEP 2-4 continues, but with a smaller part of the
array. This continues until the target element is found or until there are no elements
left.
STEP 4: Stop the program.

PROGRAM:
7 b.1 LINEAR SEARCH:
def L_search(a,e,n):
for i in range(n):
if a[i] == e:
return i+1
return -1
print("\tLINEAR SEARCH")
print("\t*************")
print("Enter list:")
29

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

a=[int(b) for b in input().split()]


e=eval(input("Enter the search element:"))
n=len(a)
pos=L_search(a,e,n)
if pos>0:
print("The element found at position:",pos)
else:
print("Element not present in the list")

OUTPUT:

Linear Search

30

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

7b.2 BINARY SEARCH:

def binary_search(arr, low, high, x):


if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid+1
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1
print("\t\tBINARY SEARCH")
print("\t\t**************")
print("Enter list:")
a=[int(b) for b in input().split()]
list.sort(a)
print("The sorted list is",a)
x=int(input("Enter the search element:"))
result = binary_search(a, 0, len(a)-1, x)
if result != -1:
print("Element is present at position:", str(result))
else:
print("Element is not present in the list")

OUTPUT:

RESULT:
The python program for creating a Searching algorithms was successfully executed.
31

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No:8
Implementation of Hash tables
Date:

AIM:
To write a Python program to implement hash table using dictionary.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Creating the hash table as a nested list.
STEP 3: Insert Data into the Hash Table.
STEP 4: Search Data from the Hash Table.
STEP 5: Delete Data from the Hash Table.
STEP 6: Stop the Program.

PROGRAM:
#create
hash_table = [[] for _ in range(10)]
print (hash_table)
#insert
def insert(hash_table, key, value):
hash_key = hash(key) % len(hash_table)
key_exists = False
bucket = hash_table[hash_key]
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
bucket[i] = ((key, value))
else:
bucket.append((key, value))

insert(hash_table, 10, 'Nepal')


insert(hash_table, 25, 'USA')
insert(hash_table, 20, 'India')
print (hash_table)

#search
def search(hash_table, key):
hash_key = hash(key) % len(hash_table)
bucket = hash_table[hash_key]

32

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

for i, kv in enumerate(bucket):
k, v = kv
if key == k:
return v

print (search(hash_table, 10)) # Output: Nepal


print (search(hash_table, 20)) # Output: India
print (search(hash_table, 30)) # Output: None

#delete
def delete(hash_table, key):
hash_key = hash(key) % len(hash_table)
key_exists = False
bucket = hash_table[hash_key]
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
del bucket[i]
print ('Key {} deleted'.format(key))
else:
print ('Key {} not found'.format(key)

delete(hash_table, 100)
print (hash_table)
delete(hash_table, 10)
print (hash_table)

OUTPUT:
[[], [], [], [], [], [], [], [], [], []]
[[(10, 'Nepal'), (20, 'India')], [], [], [], [], [(25, 'USA')], [], [], [], []]
Nepal
India
None
Key 100 not found
[[(10, 'Nepal'), (20, 'India')], [], [], [], [], [(25, 'USA')], [], [], [], []]
Key 10 deleted
[[(20, 'India')], [], [], [], [], [(25, 'USA')], [], [], [], []]

RESULT:
The python program for hash table implementation was successfully executed.

33

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex.No:9 Tree representation and traversal


Date: algorithms

AIM:
To write a Python program for tree representation and tree traversal algorithms.
ALGORITHM:
STEP 1: Start the program
STEP 2: Inorder(tree)
1. Traverse the left subtree.
2. Visit the root.
3. Traverse the right subtree.
STEP 3: Preorder(tree)
1. Visit the root.
2. Traverse the left subtree.
3. Traverse the right subtree.
STEP 4: Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.

PROGRAM:
9.1 INORDER:

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)

34

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

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:
Inorder: [10, 14, 19, 27, 31, 35, 42]

35

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

9.2 PREORDER:
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:

36

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

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

37

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

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

38

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

OUTPUT:
Inorder: [10, 14, 19, 27, 31, 35, 42]
Preorder: [27, 14, 10, 19, 35, 31, 42]
Postorder: [10, 19, 14, 31, 42, 35, 27]

RESULT:
The python program for tree traversal was successfully executed.

39

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No:10 Implementation of Binary Search Trees


Date:

AIM:
To write a Python program to implement binary search trees.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Preorder Traversal:

 Visit the root (we will print it when we visit to show the order of visiting)
 Traverse the left subtree in pre-order
 Traverse the right subtree in pre-order
STEP 3: In-order traversal:

 Traverse the left subtree in in-order


 Visit the root (we will print it when we visit to show the order of visiting)
 Traverse the right subtree in in-order
STEP 4: Post-order traversal:
 Traverse the left subtree in in-order
 Traverse the right subtree in in-order
 Visit the root (we will print it when we visit to show the order of visiting)
STEP 5: Calculate Maximum depth or Height of a tree.
STEP 6: Stop the program.

PROGRAM:
class BSTNode:
def __init__(self, val=None):
self.left = None
self.right = None
self.val = val

def insert(self, val):


if not self.val:
self.val = val
return
if self.val == val:
return

40

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

if val < self.val:


if self.left:
self.left.insert(val)
return
self.left = BSTNode(val)
return
if self.right:
self.right.insert(val)
return
self.right = BSTNode(val)
#print("RIGHT SELF VALUE=",self.val)

def get_min(self):
current = self
while current.left is not None:
current = current.left
return current.val

def get_max(self):
current = self
while current.right is not None:
current = current.right
return current.val

def delete(self, val):


if self == None:
return self
if val < self.val:
if self.left:
self.left = self.left.delete(val)
return self
if val > self.val:
if self.right:
self.right = self.right.delete(val)
return self
if self.right == None:
return self.left
if self.left == None:
return self.right
min_larger_node = self.right
while min_larger_node.left:
min_larger_node = min_larger_node.left
self.val = min_larger_node.val
self.right = self.right.delete(min_larger_node.val)
return self

def exists(self, val):


if val == self.val:
return True
if val < self.val:
if self.left == None:
41

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

return False
return self.left.exists(val)
if self.right == None:
return False
return self.right.exists(val)

def preorder(self, vals):


if self.val is not None:
vals.append(self.val)
if self.left is not None:
self.left.preorder(vals)
if self.right is not None:
self.right.preorder(vals)
return vals

def inorder(self, vals):


if self.left is not None:
self.left.inorder(vals)
if self.val is not None:
vals.append(self.val)
if self.right is not None:
self.right.inorder(vals)
return vals

def postorder(self, vals):


if self.left is not None:
self.left.postorder(vals)
if self.right is not None:
self.right.postorder(vals)
if self.val is not None:
vals.append(self.val)
return vals

nums = [12, 6, 18, 19, 21, 11, 3, 5, 4, 24, 18]


bst = BSTNode() #object creation
for num in nums:
bst.insert(num)
print("preorder:")
print(bst.preorder([]))
print("#")
print("postorder:")
print(bst.postorder([]))
print("#")
print("inorder:")
print(bst.inorder([]))
print("#")
nums = [2, 6, 20]
print("deleting " + str(nums))
for num in nums:
bst.delete(num)
print("#")
42

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

print("4 exists:")
print(bst.exists(4))
print("6 exists:")
print(bst.exists(6))
print("12 exists:")
print(bst.exists(12))
print("18 exists:")
print(bst.exists(18))

OUTPUT:
preorder:
[12, 6, 3, 5, 4, 11, 18, 19, 21, 24]
#
postorder:
[4, 5, 3, 11, 6, 24, 21, 19, 18, 12]
#
inorder:
[3, 4, 5, 6, 11, 12, 18, 19, 21, 24]
#
deleting [2, 6, 20]
#
4 exists:
True
6 exists:
False
12 exists:
True
18 exists:
True

RESULT:
The python program for creating a Stack application was successfully executed.

43

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No: 11
Implementation of Heaps
Date:

AIM:
To write a Python program for Heaps.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Create a new child node at the end of the heap (last level).

STEP 3: Add the new key to that node.


STEP 4: Move the child up until you reach the root node and the heap property is satisfied.
STEP 5: Stop the Program.

PROGRAM:
"""
Min Heap Implementation in
Python
"""
class MinHeap:
def _ _ init __(self):
"""
On this implementation the heap list is initialized
with a value
"""
self.heap_list = [0]
self.current_size = 0

def sift_up(self, i):


"""
Moves the value up in the tree to maintain the heap
property
"""
# While the element is not the root or the left element
while i // 2 > 0:
# If the element is less than its parent swap the element
if self.heap_list[i] < self.heap_list[i // 2]:
self.heap_list[i], self.heap_list[i // 2] = self.heap_list[i // 2], self.heap_list[i]
# Move the index to the parent to keep the properties
i = i // 2

def insert(self, k):


"""
Inserts a value into the heap
"""
44

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

# Append the element to the heap


self.heap_list.append(k)
# Increase the size of the heap.
self.current_size += 1
# Move the element to its position from bottom to the top
self.sift_up(self.current_size)

def sift_down(self, i):


# if the current node has at least one child
while (i * 2) <= self.current_size:
# Get the index of the min child of the current node
mc = self.min_child(i)
# Swap the values of the current element is greater than its min child
if self.heap_list[i] > self.heap_list[mc]:
self.heap_list[i], self.heap_list[mc] = self.heap_list[mc], self.heap_list[i]
i = mc

def min_child(self, i):


# If the current node has only one child, return the index of the unique child
if (i * 2)+1 > self.current_size:
return i * 2
else:
# Herein the current node has two children
# Return the index of the min child according to their values
if self.heap_list[i*2] < self.heap_list[(i*2)+1]:
return i * 2
else:
return (i * 2) + 1

def delete_min(self):
# Equal to 1 since the heap list was initialized with a value
if len(self.heap_list) == 1:
return 'Empty heap'
# Get root of the heap (The min value of the
heap) root = self.heap_list[1]
# Move the last value of the heap to the root
self.heap_list[1] = self.heap_list[self.current_size]
# Pop the last value since a copy was set on the root
*self.heap_list, _ = self.heap_list
# Decrease the size of the heap
self.current_size -= 1
# Move down the root (value at index 1) to keep the heap property
self.sift_down(1)
# Return the min value of the
heap return root

45

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

# Same tree as above example.


my_heap = MinHeap()
my_heap.insert(5)
my_heap.insert(6)
my_heap.insert(7)
my_heap.insert(9)
my_heap.insert(13)
my_heap.insert(11)
my_heap.insert(10)
print(my_heap.delete_min()) # removing min node i.e 5

OUTPUT:
5

RESULT:
The python program for creating a Heap was successfully executed.

46

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No:12 Graph representation and Traversal


Date: algorithms

AIM:
To write a Python program for Graph representation and Traversal algorithms.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Take the graph as input and find the adjacency list.
STEP 3: Start at a random vertex and visit all nodes using depth first search (DFS) and
then breadth first search (BFS).
STEP 4: Use stack for DFS and queue for BFS.
STEP 5: Stop the program.

PROGRAM:
BREADTH FIRST SEARCH PROGRAM
from queue import Queue
def bfs(graph, start):
visited = []
queue = Queue()
queue.put(start)
while not queue.empty():
vertex = queue.get()
if vertex not in visited:
visited.append(vertex)
for vert in graph[vertex]:
if vert not in visited:
queue.put(vert)
return visited

graph = {'A': set(['B', 'C']),


'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
visited = bfs(graph,'A')
print(visited)

47

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

DEPTH FIRST SEARCH


def dfs(graph,start):
visited = set()
stack = [start]
while stack:
vertex = stack.pop()
print("VERTEX",vertex)
if vertex not in visited:
visited.add(vertex)
print("GRAPH[VERTEX]:",graph[vertex])
print("GRAPH[VERTEX]-visited:",graph[vertex]-visited)
stack.extend(graph[vertex]-visited)
print("STACK:",stack)
return visited
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
vis = dfs(graph,'D')
print(vis)

OUTPUT:

Breadth first search program:


['A', 'C', 'B', 'F', 'E', 'D']
Depth first search:
VERTEX D
GRAPH[VERTEX]: {'B'}
GRAPH[VERTEX]-visited: {'B'}
STACK: ['B']
VERTEX B
GRAPH[VERTEX]: {'A', 'D', 'E'}
GRAPH[VERTEX]-visited: {'A', 'E'}
STACK: ['A', 'E']
VERTEX E
GRAPH[VERTEX]: {'F', 'B'}
GRAPH[VERTEX]-visited: {'F'}
STACK: ['A', 'F']
VERTEX F
GRAPH[VERTEX]: {'C', 'E'}
GRAPH[VERTEX]-visited: {'C'}
STACK: ['A', 'C']
48

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

VERTEX C
GRAPH[VERTEX]: {'F', 'A'}
GRAPH[VERTEX]-visited: {'A'}
STACK: ['A', 'A']
VERTEX A
GRAPH[VERTEX]: {'C', 'B'}
GRAPH[VERTEX]-visited: set()
STACK: ['A']
VERTEX A
{'F', 'D', 'A', 'B', 'E', 'C'}

RESULT:
The python program for BFS & DFS was successfully executed.

49

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No:13 Implementation of single source shortest


Date: path algorithm
AIM:
To write a Python program for single source shortest path algorithm.

ALGORITHM:
STEP 1: Initialize the distance from the source node S to all other nodes as infinite and to
itself as 0.
STEP 2: Insert the pair of < node, distance > for source i.e < S, 0 > in a DICTIONARY
STEP 3: While the DICTIONARY is not empty do
STEP 4: current_source_node = DICTIONARY . get_key (node)_with_smallest_value (dist)
Remove the key (current_source_node) from the DICTIONARY.
STEP 5: For every adjacent_node to the current_source_node do
STEP 6: if(distance[ adjacent_node ] >
length_of_path_to_adjacent_node_from_current_source + distance [ current_source_node ] )
STEP 7: distance [ adjacent_node ] = length_of_path_to_adjacent_node_from_current_source
+ distance [ current_source_node ]
STEP 8: Update the DICTIONARY with the new pair < adjacent_node,

distance [ adjacent_node ] .

PROGRAM:

from collections import defaultdict


class Node_Distance :
def __init__(self, name, dist) :
self.name = name
self.dist = dist

class Graph :
def __ init__ (self, node_count) :
# Store the adjacency list as a dictionary
# The default dictionary would create an empty list as a default (value)
# for the nonexistent keys.
self.adjlist = defaultdict(list)
self.node_count = node_count

def Add_Into_Adjlist(self, src, node_dist) :


self.adjlist[src].append(node_dist)

50

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

def Dijkstras_Shortest_Path(self, source) :


# Initialize the distance of all the nodes from the source node to infinity
distance = [999999999999] * self.node_count
# Distance of source node to itself is 0
distance[source] = 0
# Create a dictionary of { node, distance_from_source }
dict_node_length = {source: 0}
while dict_node_length :
# Get the key for the smallest value in the dictionary
# i.e Get the node with the shortest distance from the source
current_source_node = min(dict_node_length, key = lambda k: dict_node_length[k])
del dict_node_length[current_source_node]
for node_dist in self.adjlist[current_source_node] :
adjnode = node_dist.name
length_to_adjnode = node_dist.dist
# Edge relaxation
if distance[adjnode] > distance[current_source_node] + length_to_adjnode:
distance[adjnode] = distance[current_source_node] + length_to_adjnode
dict_node_length[adjnode] = distance[adjnode]
for i in range(self.node_count) :
print("Source Node ("+str(source)+") -> Destination Node(" + str(i) + ") : " +
str(distance[i]))

def main() :
g = Graph(6)
# Node 0: <1,5> <2,1> <3,4>
g.Add_Into_Adjlist(0, Node_Distance(1, 5))
g.Add_Into_Adjlist(0, Node_Distance(2, 1))
g.Add_Into_Adjlist(0, Node_Distance(3, 4))
# Node 1: <0,5> <2,3> <4,8>
g.Add_Into_Adjlist(1, Node_Distance(0, 5))
g.Add_Into_Adjlist(1, Node_Distance(2, 3))
g.Add_Into_Adjlist(1, Node_Distance(4, 8))
# Node 2: <0,1> <1,3> <3,2> <4,1>
g.Add_Into_Adjlist(2, Node_Distance(0, 1))
g.Add_Into_Adjlist(2, Node_Distance(1, 3))
g.Add_Into_Adjlist(2, Node_Distance(3, 2))
g.Add_Into_Adjlist(2, Node_Distance(4, 1))
# Node 3: <0,4> <2,2> <4,2> <5,1>
g.Add_Into_Adjlist(3, Node_Distance(0, 4)

51

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

g.Add_Into_Adjlist(3, Node_Distance(2, 2))


g.Add_Into_Adjlist(3, Node_Distance(4, 2))
g.Add_Into_Adjlist(3, Node_Distance(5, 1))
# Node 4: <1,8> <2,1> <3,2> <5,3>
g.Add_Into_Adjlist(4, Node_Distance(1, 8))
g.Add_Into_Adjlist(4, Node_Distance(2, 1))
g.Add_Into_Adjlist(4, Node_Distance(3, 2))
g.Add_Into_Adjlist(4, Node_Distance(5, 3))
# Node 5: <3,1> <4,3>
g.Add_Into_Adjlist(5, Node_Distance(3, 1))
g.Add_Into_Adjlist(5, Node_Distance(4, 3))
g.Dijkstras_Shortest_Path(0)
print("\n")
g.Dijkstras_Shortest_Path(5)

if _ _ name__== "__main __" :


main()

OUTPUT:
Source Node (0) -> Destination Node(0) : 0
Source Node (0) -> Destination Node(1) : 4
Source Node (0) -> Destination Node(2) : 1
Source Node (0) -> Destination Node(3) : 3
Source Node (0) -> Destination Node(4) : 2

Source Node (0) -> Destination Node(5) : 4


Source Node (5) -> Destination Node(0) : 4
Source Node (5) -> Destination Node(1) : 6
Source Node (5) -> Destination Node(2) : 3
Source Node (5) -> Destination Node(3) : 1
Source Node (5) -> Destination Node(4) : 3
Source Node (5) -> Destination Node(5) : 0

RESULT:
The python program for single source shortest path algorithm was successfully executed.

52

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No: 14 Implementation of minimum spanning tree


Date: algorithms

AIM:
To write a Python program for minimum spanning tree algorithms.

ALGORITHM:
STEP 1: Create a dictionary (to be used as a priority queue) PQ to hold pairs of (node,
cost).

STEP 2: Push [S, 0] ( node, cost ) in the dictionary PQ (i.e) Cost of reaching vertex S
from
source node S is zero.
STEP 3: While PQ contains ( V, C ) pairs
STEP 4: Get the adjacent node V ( key ) with the smallest edge cost ( value ) from the
d ictionary PQ.
STEP 5: Cost C = PQ [V]
STEP 6: Delete the key-value pair (V, C) from the dictionary PQ.
STEP 7: If the adjacent node V is not added to the spanning tree. STEP 8. Add node V to
the spanning tree.
STEP 9: Cost of the spanning tree += Cost C
STEP 10: For all vertices adjacent to vertex V not added to spanning
tree. STEP 11: Push pair of (adjacent node, cost ) into the dictionary
PQ.

PROGRAM:
class Node :
def __init__(self, arg_id) :
self._id = arg_id
class Graph :
def __init__(self, arg_source, arg_adj_list) :
self.source = arg_source
self.adjlist = arg_adj_list

def PrimsMST(self):
# Priority queue is implemented as a dictionary with
# key as an object of 'Node' class and value as the cost of
# reaching the node from the source.
53

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

# Since the priority queue can have multiple entries for the
# same adjacent node but a different cost, we have to use objects as
# keys so that they can be stored in a dictionary.
# [As dictionary can't have duplicate keys so objectify the key]
# The distance of source node from itself is 0. Add source node as the first node
# in the priority queue

priority_queue = { Node(self.source) : 0 }
added = [False] * len(self.adjlist)
min_span_tree_cost = 0
while priority_queue :
# Choose the adjacent node with the least edge cost
node = min (priority_queue, key=priority_queue.get)
cost = priority_queue[node]
# Remove the node from the priority queue
del priority_queue[node]
if added[node._id] == False :
min_span_tree_cost += cost
added[node._id] = True
print("Added Node : " + str(node._id) + ", cost now : "+str(min_span_tree_cost))
for item in self.adjlist[node._id] :
adjnode = item[0]
adjcost = item[1]
if added[adjnode] == False :
priority_queue[Node(adjnode)] = adjcost
return min_span_tree_cost

g1_edges_from_node = {}
# Outgoing edges from the node: (adjacent_node, cost) in graph 1.
g1_edges_from_node[0] = [ (1,1), (2,2), (3,1), (4,1), (5,2), (6,1) ]
g1_edges_from_node[1] = [ (0,1), (2,2), (6,2) ]
g1_edges_from_node[2] = [ (0,2), (1,2), (3,1) ]
g1_edges_from_node[3] = [ (0,1), (2,1), (4,2) ]
g1_edges_from_node[4] = [ (0,1), (3,2), (5,2) ]
g1_edges_from_node[5] = [ (0,2), (4,2), (6,1) ]
g1_edges_from_node[6] = [ (0,1), (2,2), (5,1) ]
g1 = Graph(0, g1_edges_from_node) cost = g1.PrimsMST()
print("Cost of the minimum spanning tree in graph 1 : " + str(cost) +"\n")
# Outgoing edges from the node: (adjacent_node, cost) in graph 2.
g2_edges_from_node = {}
g2_edges_from_node[0] = [ (1,4), (2,1), (3,5) ]
g2_edges_from_node[1] = [ (0,4), (3,2), (4,3), (5,3) ]
g2_edges_from_node[2] = [ (0,1), (3,2), (4,8) ]
g2_edges_from_node[3] = [ (0,5), (1,2), (2,2), (4,1) ]
54

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

g2_edges_from_node[4] = [ (1,3), (2,8), (3,1), (5,3) ]


g2_edges_from_node[5] = [ (1,3), (4,3) ]
g2 = Graph(0, g2_edges_from_node)
cost = g2.PrimsMST()
print("Cost of the minimum spanning tree in graph 2 : " + str(cost))

OUTPUT:
Added Node : 0, cost now : 0
Added Node : 1, cost now : 1
Added Node : 3, cost now : 2
Added Node : 4, cost now : 3
Added Node : 6, cost now : 4
Added Node : 2, cost now : 5
Added Node : 5, cost now : 6
Cost of the minimum spanning tree in graph 1 : 6
Added Node : 0, cost now : 0
Added Node : 2, cost now : 1
Added Node : 3, cost now : 3
Added Node : 4, cost now : 4
Added Node : 1, cost now : 6
Added Node : 5, cost now : 9
Cost of the minimum spanning tree in graph 2 : 9

RESULT:
The python program for minimum spanning tree algorithms was successfully executed.

55

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

Ex. No: 15
Implementation of AVL tree
Date:

AIM:
To write a Python program for AVL tree.

PROGRAM:
class node:
def __init __(self, num):
self.value = num
self.left = None
self.right = None
self.height = 1

class AVL:
def height(self, Node):
if Node is None:
return 0
else:
return Node.height

def balance(self, Node):


if Node is None:
return 0
else:
return self.height(Node.left) - self.height(Node.right)

def MinimumValueNode(self, Node):


if Node is None or Node.left is None:
return Node
else:
return self.MinimumValueNode(Node.left)

def rotateR(self, Node):


a = Node.left
b = a.right
a.right = Node
Node.left = b
Node.height = 1 + max(self.height(Node.left), self.height(Node.right))
a.height = 1 + max(self.height(a.left), self.height(a.right))
return a

56

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

def rotateL(self, Node):


a = Node.right
b = a.left
a.left = Node
Node.right = b
Node.height = 1 + max(self.height(Node.left), self.height(Node.right))
a.height = 1 + max(self.height(a.left), self.height(a.right))
return a

def insert(self, val, root):


if root is None:
return node(val)
elif val <= root.value:
root.left = self.insert(val, root.left)
elif val > root.value:
root.right = self.insert(val, root.right)
root.height = 1 + max(self.height(root.left), self.height(root.right))
balance = self.balance(root)
if balance > 1 and root.left.value > val:
return self.rotateR(root)
if balance < -1 and val > root.right.value:
return self.rotateL(root)
if balance > 1 and val > root.left.value:
root.left = self.rotateL(root.left)
return self.rotateR(root)
if balance < -1 and val < root.right.value:
root.right = self.rotateR(root.right)
return self.rotateL(root)
return root

def preorder(self, root):


if root is None:
return print(root.value)
self.preorder(root.left)
self.preorder(root.right)

def delete(self, val, Node):


if Node is None:
return Node
elif val < Node.value:
Node.left = self.delete(val, Node.left)
elif val > Node.value:
Node.right = self.delete(val, Node.right)

57

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

else:
if Node.left is None:
lt = Node.right
Node = None
return lt
elif Node.right is None:
lt = Node.left
Node = None
return lt
rgt = self.MinimumValueNode(Node.right)
Node.value = rgt.value
Node.right = self.delete(rgt.value, Node.right)
if Node is None:
return Node
Node.height = 1 + max(self.height(Node.left), self.height(Node.right))
balance = self.balance(Node)
if balance > 1 and self.balance(Node.left) >= 0:
return self.rotateR(Node)
if balance < -1 and self.balance(Node.right) <= 0:
return self.rotateL(Node)
if balance > 1 and self.balance(Node.left) < 0:
Node.left = self.rotateL(Node.left)
return self.rotateR(Node)
if balance < -1 and self.balance(Node.right) > 0:
Node.right = self.rotateR(Node.right)
return self.rotateL(Node)
return Node

Tree = AVL()
rt = None
rt = Tree.insert(3, rt)
rt = Tree.insert(5, rt)
rt = Tree.insert(7, rt)
print("PREORDER")
Tree.preorder(rt)
rt = Tree.insert(1, rt)
rt = Tree.insert(2, rt)
print("PREORDER")
Tree.preorder(rt)
rt = Tree.insert(4, rt)
rt = Tree.insert(6, rt)
rt = Tree.delete(7, rt)
rt = Tree.insert(8, rt)
rt = Tree.insert(9, rt)

58

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

print("PREORDER")
Tree.preorder(rt)
rt = Tree.delete(3, rt)
print("PREORDER")
Tree.preorder(rt)

OUTPUT:
PREORDER 5
3

PREORDER

PREORDER
3
2

PREORDER
4
2

9
59

Downloaded by Anitha A ([email protected])


lOMoARcPSD|50370378

RESULT:
The python program for implementing AVL Tree was successfully executed.

60

Downloaded by Anitha A ([email protected])

You might also like