Download as pdf or txt
Download as pdf or txt
You are on page 1of 79

An Autonomous Institution

Approved by AICTE, Affiliated to Anna University, Chennai.


ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE, IT & MECH),
Accredited by NAAC with 'A' Grade with CGPA of 3.49.
#42, Avadi-Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


191AI32A
DATA STRUCTURES LABORATORY

NAME :

REGISTER NO :

ROLL NO :

PROGRAMME :

YEAR :

SEMESTER :

1
An Autonomous Institution
Approved by AICTE, Affiliated to Anna University, Chennai.
ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE, IT & MECH),
Accredited by NAAC with 'A' Grade with CGPA of 3.49.
#42, Avadi-Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India.

CERTIFICATE
Name: ………………….……………………………..………….….…………………………..…

Year: ……………… Semester: ……………, PROGRAMME:

University Register No: College Roll No:

Certified that this is the bonafide record of work done by the above student in the
191AI32A–DATA STRUCTURES LABORATORY during the academic year 2021-22.

Signature of Head of the Department Signature of Course Incharge

Submitted for the University Practical Examination held on ………………... at VEL TECH
MULTITECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE, #42,AVADI –
VEL TECH ROAD, AVADI, CHENNAI- 600062.
Signature of Examiners

Internal Examiner:…………………… External Examiner:………………

Date:………………..

2
An Autonomous Institution
Approved by AICTE, Affiliated to Anna University, Chennai.
ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE, IT & MECH),
Accredited by NAAC with 'A' Grade with CGPA of 3.49.
#42, Avadi-Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India.

INSTITUTION VISION

• To emerge as centre for academic eminence in the field of information technology through innovative learning
practices

INSTITUTION MISSION

• To provide good teaching and learning environment for quality education in the field of information technology.
• To propagate lifelong learning.
• To impart the right proportion of knowledge, attitudes and ethics in students to enable them take up positions of
responsibility in the society and make significant contributions.

3
PROGRAMME OUTCOMES (POs)

PO’s PROGRAMME OUTCOMES


Apply knowledge of mathematics, natural science, engineering fundamentals and system
fundamentals, software development, networking & communication, and information
PO1
assurance & security to the solution of complex engineering problems in computer science
and engineering.
Ability to identify, formulate and analyze complex Computer Science and Engineering
problems in the areas of hardware, software, theoretical Computer Science and applications
PO2
to reach significant conclusions by applying Mathematics, Natural sciences, Computer
Science and Engineering principles.
Design solutions for complex computer science and engineering problems and design
PO3 systems, components or processes that meet specified needs with appropriate consideration
for public health and safety, cultural, societal, and environmental considerations.
Ability to use research based knowledge and research methods to perform literature
survey, design experiments for complex problems in designing, developing and maintaining
PO4
a computing system, collect data from the experimental outcome, analyze and interpret
valid/interesting patterns and conclusions from the data points.
Ability to create, select and apply state of the art tools and techniques in designing,
PO5
developing and testing a computing system or its component.
Apply reasoning informed by contextual knowledge to assess societal, health, safety, legal
and cultural issues and the consequent responsibilities relevant to professional engineering
PO6 practice in system development and solutions to complex engineering problems related to
system fundamentals, software development, networking & communication, and
information assurance & security.
Understand and evaluate the sustainability and impact of professional engineering work in
the solution of complex engineering problems related to system fundamentals, software
PO7
development, networking & communication, and information assurance & security in
societal and environmental contexts.
Apply ethical principles and commit to professional ethics and responsibilities and norms
PO8
of computer science and engineering practice.

Ability to function as an individual and as a team player or leader in multidisciplinary teams


PO9
and strive towards achieving a common goal.

Communicate effectively on complex engineering activities with the engineering


community and with society at large, such as being able to comprehend and write effective
PO10
reports and design documentation, make effective presentations, and give and receive clear
instructions.

4
Demonstrate knowledge and understanding of engineering management principles and
PO11 economic decision making and apply these to one’s own work, as a member and leader in a
team, to manage projects and in multidisciplinary environments.

Recognize the need for, and have the preparation and ability to engage in independent and
PO12
lifelong learning in the broadest context of technological change.

COURSE OBJECTIVES

The student should be made to:

• To implement ADT’s in python

• To design and implement linear data structures – lists, stacks, and queues

• To implement sorting, searching and hashing algorithms

• To solve problems using tree and graph structures

COURSE OUTCOMES

At the end of the course, the student should be able to

Course CO Statements
Outcome
CO1 Write functions to implement linear and non-linear data structure operations.
CO2 Suggest appropriate linear / non-linear data structure operations for solving a given problem
CO3 Appropriately use the linear / non-linear data operations for a given problem
Apply appropriate hash functions that result in a collision free scenario for data storage and
CO4
retrieval
CO5 Apply appropriate sorting and searching functions based on the application.

5
Table of Contents
Ex No. Date Name of the Experiment Page No. Teacher’s
Sign

10

11

12

13

14

6
EX.No.:1 DATE:

IMPLEMENT SIMPLE ADTS AS PYTHON CLASSES

AIM
To Implement simple ADTs as python classes.
ALGORITHM
1.Start
2. Create a class snake
3. Define the constructor and display method
4. Display result
5. Stop
PROGRAM
class snake:
def __init__(self, name):
self.name= name
def display(self, new_name):
self.name1= new_name
return self.name1
python= snake("Deepak")
print(python.name)
print(python.display("Yeswanth"))

OUTPUT
Deepak
Yeswanth

RESULT:
Thus the program to implement simple ADTs as python classes is performed.

7
EX. No.:2 DATE:

IMPLEMENT RECURSIVE ALGORITHM IN PYTHON

AIM:
To Write a python program to implement recursive algorithms in python.

ALGORITHM
1. Start
2. Get a non negative integer n
3. if(n=0),return 1
4. Else return Factorial (n-1)*n
5. Return factorial value
6. Stop

PROGRAM
def fact(n):
if n ==1:
return n
else:
return n*fact(n-1)
num = eval(input("Enter the n value: "))
if num<0:
print("Invalid input! please enter a positive number")
elif num ==0:
print("factorial of number 0 is 1")
else:
print(f"fatorial of number {num} = {fact(num)}")

OUTPUT
Enter the n value: 5
fatorial of number 5 = 120

RESULT
Thus the program to implement recursive algorithms in python was written and executed
successfully.

8
EX.No.:3 DATE:

IMPLEMENT LIST ADT USING PYTHON ARRAYS

AIM
To Write a python program to implement list ADT using python arrays.

ALGORITHM
1. Start
2. Create and initialize an array List
3. Perform the following operation such as insert, delete, remove and reversing the element
4. Display the result
5. Stop

PROGRAM
def display(a):
print("Array contains:")
for i in range(0,len(a)):
print(a[i])
import array as myarr
a= myarr.array("b", [2,4,6,8,10])
print(a)
a.insert(2,56)
display(a)
a[0]= 15
display(a)
a.pop(2)
a.remove(8)
display(a)
print("The index of 10 is",a.index(10))
a.reverse()
print("The reversed array:")
display(a)

OUTPUT
array('b', [2, 4, 6, 8, 10])
Array contains:
2
4
56
6
8

9
10
Array contains:
15
4
56
6
8
10
Array contains:
15
4
6
10
The index of 10 is 3
The reversed array:
Array contains:
10
6
4
15

RESULT

Thus a C Program for Leap year checking was executed and the output was obtained.

10
EX.No.:4(A) DATE:

IMPLEMENTATIONS OF SINGLE LINKED LIST

AIM
To Write a python program to implement Single Linked List Implementation of list.

ALGORITHM
1. Define node class and SLL Class
2. Start with a single node. Let's start with a single node since linking several nodes gives us a
complete list.
3. Join nodes to get a linked list. ...
4. Add required methods to the SLL class.
5. Perform the following operation such as add, search, display, remove.
6. Display the result.

PROGRAM
class Node:
def __init__(self, val):
self.value = val
self.next = None
class SLL:
def __init__(self):
self.head = None
def add(self, val):
if self.empty() is True:
self.head = Node(val)
print("Head value created")
return
opt = int(input("Enter 1 to add a Node at the beginning\nEnter 2 to add a Node at the
end\nEnter 3 to add a Node in the middle::"))
if opt == 1:
a = Node(val)
a.next = self.head
self.head = a
elif opt == 2:
i = self.head
while i.next is not None:
i = i.next
i.next = Node(val)
elif opt == 3:
pos = int(input("Enter the position ::"))
i=1
n = self.head
f = n.next
11
flag = 0
while f is not None:
if i == pos:
flag = 1
break
f = f.next
n = n.next
i=i+1
if flag == 1:
n.next = Node(val)
n.next.next = f
else:
print("Position not found")
def delete(self):
if self.empty() is True:
print("Linked List empty")
return
elif self.head.next is None:
self.head = None
return
opt = int(input("Enter 1 to delete the beginning element\nEnter 2 to delete the last”
“element\nEnter 3 to delete elements in between ::"))
if opt == 1:
self.head = self.head.next
elif opt == 2:
n = self.head
while n.next.next is not None:
n = n.next
n.next = None
else:
op = int(input("Enter 1 to delete by position\nEnter 2 to delete by value ::"))
if op == 1:
pos = int(input("Enter the position ::"))
i=1
n = self.head
f = self.head.next
flag = 0
while f.next is not None:
if i == pos:
flag = 1
break
i=i+1
n = n.next
f = f.next
if flag == 1:
n.next = f.next
else:
print("Position not found")
return

12
else:
val = int(input("Enter the value you want to delete ::"))
n = self.head
f = self.head.next
flag = 0
while f.next is not None:
if f.value == val:
flag = 1
break
f = f.next
n = n.next
if flag == 1:
n.next = f.next
else:
print("Value not found")
return
def clear(self):
self.head = None
print("Linked List cleared")
def empty(self):
if self.head is None:
return True
else:
return False
def display(self):
if self.empty() is True:
print("Linked List empty")
return
print("THE LINKED LIST")
print(self.head.value, " <== HEAD")
n = self.head.next
while n is not None:
print(n.value)
n = n.next
print("Linked List ends")
LL = SLL()
while True:
option = int(input("Enter 1 to add an element\nEnter 2 to delete an element\nEnter 3”
“to clear the Linked List\nEnter 4 to display the Linked List\nEnter 5 to exit ::"))
if option == 1:
value = int(input("Enter the value you want to add ::"))
LL.add(value)
continue
elif option == 2:
LL.delete()
continue
elif option == 3:
LL.clear()
continue

13
elif option == 4:
LL.display()
continue
elif option == 5:
print("Goodbye")
break
elif option == 6:
print(LL.empty())
else:
print("Wrong option")

OUTPUT
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::1
Enter the value you want to add ::25
Head value created
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::4
THE LINKED LIST
25 <== HEAD
Linked List ends
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::2
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::4
Linked List empty
Enter 1 to add an element
Enter 2 to delete an element

14
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::3
Linked List cleared
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::5
Goodbye

RESULT
Thus, operations on single linked list implementation have been executed successfully.

15
EX.No.:4(B) DATE:

IMPLEMENTATIONS OF DOUBLY LINKED LIST

AIM
To Write a python program to implement Doubly Linked List Implementations of list.

ALGORITHM
1. Create a Class Node.
2. Create a Class Doubly Linked List.
3. Define the __init__ method.
4. Define the append and insert method.
5. Define the remove method.
6. Insert the element and perform the following operation Append, insert, display, size, remove
functions.
7. Display the elements.

PROGRAM
class Node:
def __init__(self, val):
self.value = val
self.left = None
self.right = None
class DLL:
def __init__(self):
self.head1 = None
self.head2 = None
def add(self, val):
if self.empty() is True:
self.head1 = Node(val)
self.head2 = self.head1
print("Head value created")
return
opt = int(input("Enter 1 to add a Node at the beginning\nEnter 2 to add a Node at the”
“end\nEnter 3 to add a Node before a node\nEnter 4 to add a Node after a node ::"))
if opt == 1:
a = Node(val)
a.right = self.head1
self.head1.left = a
self.head1 = self.head1.left
elif opt == 2:
a = Node(val)
self.head2.right = a
a.left = self.head2
self.head2 = self.head2.right
16
elif opt == 3:
pos = int(input("Enter the position ::"))
i=1
n = self.head1.right
flag = 0
while n is not None:
if i == pos:
flag = 1
break
n = n.right
i=i+1
if flag == 1:
a = Node(val)
a.right = n
n.left.right = a
a.left = n.left
n.left = a
else:
print("Position not found")
elif opt == 4:
pos = int(input("Enter the position ::"))
i=0
n = self.head1
flag = 0
while n.right is not None:
if i == pos:
flag = 1
break
n = n.right
i=i+1
if flag == 1:
a = Node(val)
n.right.left = a
a.right = n.right
a.left = n
n.right = a
else:
print("Position not found")
else:
print("Wrong option")
def delete(self):
if self.empty() is True:
print("Linked List empty")
return
elif self.head1.right is None:
self.head1 = None
self.head2 = None
return
opt = int(input("Enter 1 to delete the beginning element\nEnter 2 to delete the last

17
element\nEnter 3 to delete elements in between ::"))
if opt == 1:
self.head1 = self.head1.right
self.head1.left = None
elif opt == 2:
self.head2 = self.head2.left
self.head2.right = None
else:
op = int(input("Enter 1 to delete by position\nEnter 2 to delete by value ::"))
if op == 1:
pos = int(input("Enter the position ::"))
i=1
n = self.head1.right
flag = 0
while n.right is not None:
if i == pos:
flag = 1
break
i=i+1
n = n.right
if flag == 1:
n.left.right = n.right
n.right.left = n.left
else:
print("Position not found")
return
else:
val = int(input("Enter the value you want to delete ::"))
n = self.head1
flag = 0
while n.right is not None:
if n.value == val:
flag = 1
break
n = n.right
if flag == 1:
n.left.right = n.right
n.right.left = n.left
else:
print("Value not found")
return
def clear(self):
self.head1 = None
self.head2 = None
print("Linked List cleared")
def empty(self):
if self.head1 is None:
return True
else:

18
return False
def display(self):
if self.empty() is True:
print("Linked List empty")
return
elif self.head1.right is None:
print("LINKED LIST")
print(self.head1.value, "HEAD 1 & 2")
print("Linked List ends")
return
o = int(input("Enter 1 to print in forward direction\nEnter 2 to print in backward”
“direction ::"))
print("LINKED LIST")
if o == 1:
print(self.head1.value, " <== HEAD 1")
n = self.head1.right
while n is not self.head2:
print(n.value)
n = n.right
print(self.head2.value, " <== HEAD 2")
print("Linked List ends")
elif o == 2:
print(self.head2.value, " <== HEAD 2")
n = self.head2.left
while n is not self.head1:
print(n.value)
n = n.left
print(self.head1.value, " <== HEAD 1")
print("Linked List ends")
else:
print("Wrong option")
LL = DLL()
while True:
option = int(input("Enter 1 to add an element\nEnter 2 to delete an element\nEnter 3 to”
“clear the Linked List\nEnter 4 to display the Linked List\nEnter 5 to exit ::"))
if option == 1:
value = int(input("Enter the value you want to add ::"))
LL.add(value)
continue
elif option == 2:
LL.delete()
continue
elif option == 3:
LL.clear()
continue
elif option == 4:
LL.display()
continue
elif option == 5:

19
print("Goodbye")
break
elif option == 6:
print(LL.empty())
else:
print("Wrong option")

OUTPUT
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::1
Enter the value you want to add ::25
Head value created
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::1
Enter the value you want to add ::26
Enter 1 to add a Node at the beginning
Enter 2 to add a Node at the end
Enter 3 to add a Node before a node
Enter 4 to add a Node after a node ::1
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::4
Enter 1 to print in forward direction
Enter 2 to print in backward direction ::1
LINKED LIST
26 <== HEAD 1
25 <== HEAD 2
Linked List ends
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
20
Enter 4 to display the Linked List
Enter 5 to exit ::5
Goodbye

RESULT
Thus, Doubly Linked List implementation of List is performed.

21
EX.No.:4(C) DATE:

IMPLEMENTATION OF CIRCULAR SINGLE LINKED LIST

AIM
To Write a python program for Circular Linked List Implementations of list.

ALGORITHM
1. Create a Class Node
2. Create a CSLL
3. Define the constrcutor
4. Define the append and insert method
5. Define the remove method
6. Insert the element and perform the following operation append, insert, display, size, remove
function
7. Display the elements

PROGRAM
class Node:
def __init__(self, val):
self.value = val
self.next = None
class CSLL:
def __init__(self):
self.head = None
def add(self, val):
if self.empty() is True:
self.head = Node(val)
self.head.next = self.head
print("Head value created")
return
opt = int(input("Enter 1 to add a Node at the beginning\nEnter 2 to add a Node at the
end\nEnter 3 to add a Node in the middle::"))
if opt == 1:
a = Node(val)
a.next = self.head
n = self.head
while n.next is not self.head:
n = n.next
n.next = a
self.head = a
elif opt == 2:
i = self.head
while i.next is not self.head:
i = i.next
22
i.next = Node(val)
i.next.next = self.head
elif opt == 3:
pos = int(input("Enter the position ::"))
i=1
n = self.head
f = n.next
flag = 0
while f is not self.head:
if i == pos:
flag = 1
break
f = f.next
n = n.next
i=i+1
if flag == 1:
n.next = Node(val)
n.next.next = f
else:
print("Position not found")
def delete(self):
if self.empty() is True:
print("Linked List empty")
return
elif self.head.next is self.head:
self.head = None
return
opt = int(input("Enter 1 to delete the beginning element\nEnter 2 to delete the last
element\nEnter 3 to delete elements in between ::"))
if opt == 1:
n = self.head
while n.next is not self.head:
n = n.next
n.next = self.head.next
self.head = self.head.next
elif opt == 2:
n = self.head
while n.next.next is not self.head:
n = n.next
n.next = self.head
else:
op = int(input("Enter 1 to delete by position\nEnter 2 to delete by value ::"))
if op == 1:
pos = int(input("Enter the position ::"))
i=1
n = self.head
f = self.head.next
flag = 0
while f.next is not self.head:

23
if i == pos:
flag = 1
break
i=i+1
n = n.next
f = f.next
if flag == 1:
n.next = f.next
else:
print("Position not found")
return
else:
val = int(input("Enter the value you want to delete ::"))
n = self.head
f = self.head.next
flag = 0
while f.next is not self.head:
if f.value == val:
flag = 1
break
f = f.next
n = n.next
if flag == 1:
n.next = f.next
else:
print("Value not found")
return
def clear(self):
self.head = None
print("Linked List cleared")
def empty(self):
if self.head is None:
return True
else:
return False
def display(self):
if self.empty() is True:
print("Linked List empty")
return
print("THE LINKED LIST")
print(self.head.value, " <== HEAD")
n = self.head.next
while n is not self.head:
print(n.value)
n = n.next
print("Linked List ends")
LL = CSLL()
while True:

24
option = int(input("Enter 1 to add an element\nEnter 2 to delete an element\nEnter 3 to clear
the Linked List\nEnter 4 to display the Linked List\nEnter 5 to exit ::"))
if option == 1:
value = int(input("Enter the value you want to add ::"))
LL.add(value)
continue
elif option == 2:
LL.delete()
continue
elif option == 3:
LL.clear()
continue
elif option == 4:
LL.display()
continue
elif option == 5:
print("Goodbye")
break
elif option == 6:
print(LL.empty())
else:
print("Wrong option")

OUTPUT
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::1
Enter the value you want to add ::30
Head value created
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::4
THE LINKED LIST
30 <== HEAD
Linked List ends
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
25
Enter 5 to exit ::1
Enter the value you want to add ::50
Enter 1 to add a Node at the beginning
Enter 2 to add a Node at the end
Enter 3 to add a Node in the middle::2
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::4
THE LINKED LIST
30 <== HEAD
50
Linked List ends
Enter 1 to add an element
Enter 2 to delete an element
Enter 3 to clear the Linked List
Enter 4 to display the Linked List
Enter 5 to exit ::5
Goodbye

RESULT

Thus the circular linked list and its operations were implemented successfully.
26
EX.No.:5(A) DATE:

IMPLEMENTATION OF STACK ADTS

AIM
To Write a Python script to implement stack ADTS.

ALGORITHM
Step 1:Start the program
Step 2:The process of putting a new data element onto stack, Push operation involves Checks if
the stack is full ,produces an error and exit.
Step 3: If the stack is not full, increments top to point next empty space. Adds data element to the
stack location, where top is pointing.
Step 4: A Pop operation may involve Checks if the stack is empty, produces an error and exit.
Step 5: Display the elements in the list
Step 6: Stop

PROGRAM
class stack:
def __init__(self):
self.tops = -1
self.stack_ds = []
def push(self, val):
self.stack_ds.append(val)
self.tops += 1
def pop(self):
if self.empty() is True:
print("Stack empty")
return
self.tops -= 1
return self.stack_ds.pop()
def top(self):
if self.empty() is True:
print("Stack empty")
return
return self.tops
def empty(self):
if self.tops == -1:
return True
27
else:
return False
a = stack()
a.push(1)
a.push(2)
print(a.stack_ds)
print(a.pop())
print(a.stack_ds)
print(a.top())
print(a.empty())

OUTPUT
[1, 2]
2
[1]
0
False

RESULT
Thus the stack ADT has been implemented successfully.

28
EX.No.:5(B) DATE:

IMPLEMENTATION OF QUEUE ADTS

AIM
To Write a Python script to implement queue ADTS..

ALGORITHM
1. Queue operations may involve initializing or defining the queue, utilizing it, and then
completely erasing it from the memory.
2. This function helps to see the data at the front of the queue. The algorithm of peek() ,
Implementation of peek() function
3. We just check for the rear pointer to reach at MAXSIZE to determine that the queue is
full, Implementation of isfull() function
4. If the value of front is less than MIN or 0, it tells that the queue is not yet initialized,
hence empty.
5. Check if the queue is full produce overflow error and exit.
6. If the queue is not full, increment rear pointer to point the next empty space.
7. Add data element to the queue location, where the rear is pointing.
8. Check if the queue is empty. produce underflow error and exit.
9. If the queue is not empty, access the data where front is pointing. Increment front pointer
to point to the next available data element

PROGRAM
front= 0
rear= 0
mymax= 3
def createQueue():
queue= []
return queue
def isempty(queue):
return len(queue) ==0
def enqueue(queue, item):
queue.append(item)
def dequeue(queue):
if(isempty(queue)):
return "queue is empty"
item=queue[0]

29
del queue[0]
return item
queue= createQueue()
while True:
print("1 Enqueue\n2 Dequeue\n3 Display\n4 Quit\n")
ch= int(input("Enter choice"))
if ch==1:
if rear<mymax:
item= input("Enter item")
enqueue(queue,item)
rear+= 1
else:
print("Queue is full")
elif ch==2:
print(dequeue(queue))
elif ch==3:
print(queue)
else:
break

OUTPUT
1 Enqueue
2 Dequeue
3 Display
4 Quit

Enter choice1
Enter item8
1 Enqueue
2 Dequeue
3 Display
4 Quit

Enter choice3
['8']
1 Enqueue
2 Dequeue
3 Display

30
4 Quit

Enter choice2
8
1 Enqueue
2 Dequeue
3 Display
4 Quit

Enter choice4

RESULT
Thus the QUEUE ADT has been implemented successfully.
31
EX.No.:6(A) DATE:

APPLICATIONS OF STACK
INFIX EXPRESSION INTO POSTFIX EXPRESSION CONVERSION

AIM
To write a Python program to convert the Infix Expression into Postfix Expression using Stack.

ALGORITHM
1. Start
2. Expression evaluation and syntax parsing
3. Backtracking: The prototypical example of a backtracking algorithm is depth-first search,
which finds all vertices of a graph that can be reached from a specified starting vertex
4. Books kept one above another.
5. Matching parenthesis by compiler.
6. To reverse a word
7. An “undo” mechanism in text editors.
8. Stack of books
9. Pushdown Automata
10. Memory Management
11. Evaluating prefix, postfix and infix expressions.
12. Stop

PROGRAM
class infix_to_postfix:
precedence={'^':5,'*':4,'/':4,'+':3,'-':3,'(':2,')':1}
def __init__(self):
self.items=[]
self.size=-1
def push(self,value):
self.items.append(value)
self.size+=1
def pop(self):
if self.isempty():
return 0
else:
self.size-=1
return self.items.pop()
def isempty(self):
32
if(self.size==-1):
return True
else:
return False
def seek(self):
if self.isempty():
return false
else:
return self.items[self.size]
def isOperand(self,i):
if i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
return True
else:
return False
def infixtopostfix (self,expr):
postfix=""
print('postfix expression after every iteration is:')
for i in expr:
if(len(expr)%2==0):
print("Incorrect infix expr")
return False
elif(self.isOperand(i)):
postfix +=i
elif(i in '+-*/^'):
while(len(self.items)and self.precedence[i]<=self.precedence[self.seek()]):
postfix+=self.pop()
self.push(i)
elif i is '(':
self.push(i)
elif i is ')':
o=self.pop()
while o!='(':
postfix +=o
o=self.pop()
print(postfix)
#end of for
while len(self.items):
if(self.seek()=='('):

33
self.pop()
else:
postfix+=self.pop()
return postfix
s=infix_to_postfix()
expr=input('enter the expression ')
result=s.infixtopostfix(expr)
if (result!=False):
print("the postfix expr of :",expr,"is",result)

OUTPUT
enter the expression G+A+(U-R)^I
postfix expression after every iteration is:
G
G
GA
GA+
GA+
GA+U
GA+U
GA+UR
GA+UR-
GA+UR-
GA+UR-I
the postfix expr of : G+A+(U-R)^I is GA+UR-I^+

RESULT
Thus the postfix expression of infix expression : G+A+(U-R)^I is GA+UR-I^+

34
EX.No.:6(B) DATE:

APPLICATION OF QUEUES
FIRST COME FIRST SERVED (FCFS) SCHEDULING

AIM
To write a Python program for First Come First Served Scheduling using Queue.

ALGORITHM
1. A Non-Preemptive scheduling algorithm. FIFO (First In First Out)
2. Strategy assigns priority to process in the order in which they request the processor.
3. The process that requests the CPU first is allocated the CPU first.
4. This is easily implemented with a FIFO queue for managing the tasks.
5. As the process come in, they are put at the end of the queue.
6. As the CPU finishes each task, it removes it from the start of the queue and heads on to the
next task.

PROGRAM
def findWaitingTime(processes, n,bt, wt):
wt[0] = 0
for i in range(1, n ):
wt[i] = bt[i - 1] + wt[i - 1]
def findTurnAroundTime(processes, n,bt, wt, tat):
for i in range(n):
tat[i] = bt[i] + wt[i]
def findavgTime( processes, n, bt):
wt = [0] * n
tat = [0] * n
total_wt = 0
total_tat = 0
findWaitingTime(processes, n, bt, wt)
findTurnAroundTime(processes, n,bt, wt, tat)
print( "Processes Burst time " +" Waiting time " +" Turn around time")
for i in range(n):
total_wt = total_wt + wt[i]
total_tat = total_tat + tat[i]
print(" " + str(i + 1) + "\t\t"+str(bt[i]) + "\t "+str(wt[i]) +"\t\t "+str(tat[i]))
print( "Average waiting time = "+str(total_wt / n))

35
print("Average turn around time = "+str(total_tat / n))
if __name__ =="__main__":
processes = [ 1, 2, 3]
n = len(processes)
burst_time = [10, 5, 8]
findavgTime(processes, n, burst_time)

OUTPUT
Processes Burst time Waiting time Turn around time
1 10 0 10
2 5 10 15
3 8 15 23
Average waiting time = 8.333333333333334
Average turn around time = 16.0

RESULT
Thus a python program for First Come First Served Scheduling using Queue is executed
successfully.

36
EX.NO.:7(A) DATE:

IMPLEMENTATION OF SORTING AND SEARCHING ALGORITHMS


BUBBLE SORT

AIM
To sort an array of N numbers using Bubble sort

ALGORITHM
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Outer Index i varies from last element to first element
a. Index j varies from first element to i-1
i. Compare elements Aj and Aj+1
ii. If out-of-order then swap the elements
5. Display array elements after each pass
6. Display the final sorted list
7. Stop

PROGRAM
def bubbleSort(nlist):
for passnum in range(len(nlist)-1,0,-1):
for i in range(passnum):
if nlist[i]>nlist[i+1]:
temp = nlist[i]
nlist[i] = nlist[i+1]
nlist[i+1] = temp
nlist = [14,46,43,27,57,41,45,21,70]
bubbleSort(nlist)
print(nlist)

OUTPUT
[14, 21, 27, 41, 43, 45, 46, 57, 70]

RESULT
Thus an array was sorted using bubble sort.

37
EX.NO.:7(B) DATE:

IMPLEMENTATION OF SORTING AND SEARCHING ALGORITHMS


SELECTION SORT

AIM
To sort an array of N numbers using Selection sort.

ALGORITHM
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Outer index varies from first to last but one element
a. Inner index is used to compare from i+1th element to last element.
i. Find the smallest element.
b. Swap i th element and the smallest element
c. Display the array elements after each pass
5. Display the sorted array elements.
6. Stop

PROGRAM
def selectionSort(nlist):
for fillslot in range(len(nlist)-1,0,-1):
maxpos=0
for location in range(1,fillslot+1):
if nlist[location]>nlist[maxpos]:
maxpos = location
temp = nlist[fillslot]
nlist[fillslot] = nlist[maxpos]
nlist[maxpos] = temp
nlist = [14,46,43,27,57,41,45,21,70]
selectionSort(nlist)
print(nlist)
OUTPUT
[14, 21, 27, 41, 43, 45, 46, 57, 70]

RESULT
Thus an array was sorted using Selection sort.
38
EX.NO.:7(C) DATE:

IMPLEMENTATION OF SORTING AND SEARCHING ALGORITHMS


INSERTION SORT

AIM
To sort an array of N numbers using Insertion sort.

ALGORITHM
1. Read the number of elements for the list from the user.
2. Define the function for insertion Sort
3. Then initialize the loop as follows.
For i in range (1, len(alist)
4. Using While loop check the condition
Position > 0 and alist[position-1]>currentvalue
5. If the condition is true swap the values by changing the position.
6. Print the sorted list

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

39
OUTPUT
Sorted array is:
5
6
11
12
13

RESULT
Thus an array was sorted using Insertion sort

40
EX.No.:7(D) DATE:

IMPLEMENTATION OF SORTING AND SEARCHING ALGORITHMS


MERGE SORT

AIM
To sort an array of N numbers using Merge sort

ALGORITHM
1. Start
2. Read number of array elements n
3. Read array elements 4. Divide the array into sub-arrays with a set of elements
5. Recursively sort the sub-arrays
6. Display both sorted sub-arrays
7. Merge the sorted sub-arrays onto a single sorted array.
8. Display the merge sorted array elements
9. Stop

PROGRAM
def mergeSort(nlist):
print("Splitting ",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
nlist[k]=lefthalf[i]
i=i+1
41
k=k+1
while j < len(righthalf):
nlist[k]=righthalf[j]
j=j+1
k=k+1
nlist = [14,46,43,27,57,41,45,21,70]
print("Merging ",nlist)
mergeSort(nlist)
print(nlist)

OUTPUT
Merging [14, 46, 43, 27, 57, 41, 45, 21, 70]
Splitting [14, 46, 43, 27, 57, 41, 45, 21, 70]
Splitting [14, 46, 43, 27]
Splitting [14, 46]
Splitting [14]
Splitting [46]
Splitting [43, 27]
Splitting [43]
Splitting [27]
Splitting [57, 41, 45, 21, 70]
Splitting [57, 41]
Splitting [57]
Splitting [41]
Splitting [45, 21, 70]
Splitting [45]
Splitting [21, 70]
Splitting [21]
Splitting [70]
[14, 21, 27, 41, 43, 45, 46, 57, 70]

RESULT
Thus an array was sorted using Merge sort

42
EX. NO.:7(E) DATE:

IMPLEMENTATION OF SORTING AND SEARCHING ALGORITHMS


QUICK SORT

AIM
To sort an array of N numbers using Quick sort.

ALGORITHM
1. Start
2. Read number of array elements n
3. Read array elements A
4. Select an pivot element x
5. Divide the array into 3 sequences: elements < x, x, elements > x
6. Recursively quick sort both sets (Ai < x and Ai > x)
7. Display the sorted array elements
8. Stop

PROGRAM
def quickSort(data_list):
quickSortHlp(data_list,0,len(data_list)-1)
def quickSortHlp(data_list,first,last):
if first < last:
splitpoint = partition(data_list,first,last)
quickSortHlp(data_list,first,splitpoint-1)
quickSortHlp(data_list,splitpoint+1,last)
def partition(data_list,first,last):
pivotvalue = data_list[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:
leftmark = leftmark + 1
while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = True

43
else:
temp = data_list[leftmark]
data_list[leftmark] = data_list[rightmark]
data_list[rightmark] = temp
temp = data_list[first]
data_list[first] = data_list[rightmark]
data_list[rightmark] = temp
return rightmark
data_list = [54,26,93,17,77,31,44,55,20]
quickSort(data_list)
print(data_list)

OUTPUT
[17, 20, 26, 31, 44, 54, 55, 77, 93]

RESULT
Thus an array was sorted using Quick sort.

44
EX.NO.:7(F) DATE:

IMPLEMENTATION OF SORTING AND SEARCHING ALGORITHMS


LINEAR SEARCH

AIM
To perform linear search of an element on the given array.

ALGORITHM
1. Start
2. Read number of array elements n
3. Read array elements Ai, i = 0,1,2,…n– 1
4. Read search value
5. Assign 0 to found
6. Check each array element against search
a. If Ai = search then
i. found = 1
ii. Print "Element found"
iii. Print position i
iv. Stop
7. If found = 0 then
8. print "Element not found"
9. Stop

PROGRAM
def Sequential_Search(dlist, item):
pos = 0
found = False
while pos < len(dlist) and not found:
if dlist[pos] == item:
found = True
else:
pos = pos + 1
return found, pos
print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))

OUTPUT
(True, 3)

45
RESULT
Thus an array was linearly searched for an element's existence.

46
EX.NO.:7(G) DATE:

IMPLEMENTATION OF SORTING AND SEARCHING ALGORITHMS


BINARY SEARCH

AIM
To locate an element in a sorted array using Binary search method.

ALGORITHM
1. Start
2. Read number of array elements, say n
3. Create an array consisting n sorted elements
4. Get element, say key to be located
5. Assign 0 to lower and n to upper
6. While (lower < upper)
a. Determine middle element
b. mid = (upper+lower)/2
c. If key = arr[mid] then
i. Print mid
ii. Stop
d. Else if key > arr[mid] then
i. lower = mid + 1
e. else
i. upper = mid – 1
7. Print "Element not found"
8. Stop

PROGRAM
def binary_search(item_list,item):
first = 0
last = len(item_list)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
else:
if item < item_list[mid]:

47
last = mid - 1
else:
first = mid + 1
return found
print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))

OUTPUT
False
True

RESULT
Thus an element is located quickly using binary search method.

48
EX.NO.:8 DATE:

IMPLEMENTATION OF HASH TABLES

AIM
To write a Python Program to implement the Hash Table.

ALGORITHM
1. Start the Program
2. Create a Hash table using list.
3. Compute the hash code of the key passed and locate the element using that hash code
as index in the list.
4. Insert − inserts an element in a hash table.
5. Display – To display the contents of the Hash table.
6. End the Program

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)

49
OUTPUT
0 --> Allahabad --> Mathura
1 --> Punjab --> Noida
2
3
4
5 --> Mumbai
6
7
8
9 --> Delhi

RESULT
Thus the Hash table has been implemented successfully.

50
EX.NO.:9 DATE:

TREE REPRESENTATION AND TRAVERSAL ALGORITHM

AIM
To perform linear search of an element on the given array.

ALGORITHM
1. Start
2. Create a class Node
3. Inorder(tree)
1. Traverse the left subtree
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
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.
5. Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
6. Display the result
7. Stop

PROGRAM
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left)
print(root.val),
printInorder(root.right)

51
def printPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
print(root.val),
def printPreorder(root):
if root:
print(root.val),
printPreorder(root.left)
printPreorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Preorder traversal of binary tree is")
printPreorder(root)
print("\nInorder traversal of binary tree is")
printInorder(root)
print("\nPostorder traversal of binary tree is")
printPostorder(root)

OUTPUT
Preorder traversal of binary tree is
1
2
4
5
3
Inorder traversal of binary tree is
4
2
5
1
3
Postorder traversal of binary tree is
4
5

52
2
3
1

RESULT
Thus an array was linearly searched for an element's existence.

53
EX.NO.:10 DATE:

IMPLEMENTATION OF BINARY SEARCH TREE

AIM
To Write a Python program to create a Balanced Binary Search Tree (BST) using Preorder Traversal.

ALGORITHM
1. Start the Program
2. Pre-order traversal_In this traversal technique the traversal order is root-left-right
2.1. Process data of root node
2.2. First, traverse left subtree completely
2.3. Then, traverse right subtree
3. Post-order traversal_In this traversal technique the traversal order is left-right-root.
3.1. Process data of left subtree
3.2. First, traverse right subtree
3.3. Then, traverse root node
4. In-order traversal_In in-order traversal, do the following:
4.1. First process left subtree (before processing root node)
4.2. Then, process current root node
4.3. Process right subtree
5. 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
if val < self.val:
if self.left:
self.left.insert(val)

54
return
self.left = BSTNode(val)
return
if self.right:
self.right.insert(val)
return
self.right = BSTNode(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

55
def exists(self, val):
if val == self.val:
return True
if val < self.val:
if self.left == None:
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()
for num in nums:
bst.insert(num)

56
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("#")
print("4 exists:")
print(bst.exists(4))
print("2 exists:")
print(bst.exists(2))
print("12 exists:")
print(bst.exists(12))
print("18 exists:")
print(bst.exists(18))

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

57
False
12 exists:
True
18 exists:
True

RESULT
Thus the implementation of Balanced Binary Search Tree (BST) using linked list has been done
successfully.
58
EX.NO.:11 DATE:

IMPLEMENTATION OF HEAPS

AIM
To write a Python program to implement priority-queue using array implementation of binary heap.
ALGORITHM
1. Start
2. Create the priority queue by inserting the elements one by one.
3. While inserting a new node, check for the condition (i > 0 and H[parent(i)] < H[i]) to
shift up.
4. Display the contents.
5. Find the node with maximum priority
6. Display the contents of Priority Queue after extracting maximum
7. Stop

PROGRAM
H =[0] * 50
size = -1
def parent (i):
return (i - 1)// 2
def leftChild (i):
return ((2 * i) + 1)
def rightChild (i):
return ((2 * i) + 2)
def shiftUp (i):
while (i > 0 and H[parent (i)] < H[i]):
swap (parent (i), i)
i = parent (i)
def shiftDown (i):
maxIndex = i
l = leftChild (i)
if (l <= size and H[l] > H[maxIndex]):
maxIndex = l
r = rightChild (i)
if (r <= size and H[r] > H[maxIndex]):
maxIndex = r
if (i != maxIndex):

59
swap(i, maxIndex)
shiftDown(maxIndex)
def insert(p) :
global size
size = size + 1
H[size] = p
shiftUp(size)
def extractMax():
global size
result = H[0]
H[0] = H[size]
size = size - 1
shiftDown(0)
return result
def changePriority(i,p):
oldp = H[i]
H[i] = p
if (p > oldp):
shiftUp(i)
else:
shiftDown(i)
def getMax() :
return H[0]
def Remove(i) :
H[i] = getMax() + 1
shiftUp(i)
extractMax()
def swap(i, j) :
temp = H[i]
H[i] = H[j]
H[j] = temp
insert(45)
insert(20)
insert(14)
insert(12)
insert(31)
insert(7)
insert(11)

60
insert(13)
insert(7)
i=0
print("Priority Queue : ", end = "")
while (i <= size):
print(H[i], end = " ")
i += 1
print()
print("Node with maximum priority :" , extractMax())
print("Priority queue after extracting maximum : ", end = "")
j=0
while (j <= size) :
print(H[j], end = " ")
j += 1
print()
changePriority(2, 49)
print("Priority queue after priority change : ", end = "")
k=0
while (k <= size) :
print(H[k], end = " ")
k += 1
print()
Remove(3)
print("Priority queue after removing the element : ", end = "")
l=0
while (l <= size) :
print(H[l], end = " ")
l += 1

OUTPUT
Priority Queue : 45 31 14 13 20 7 11 12 7
Node with maximum priority : 45
Priority queue after extracting maximum : 31 20 14 13 7 7 11 12
Priority queue after priority change : 49 20 31 13 7 7 11 12
Priority queue after removing the element : 49 20 31 12 7 7 11

RESULT
Thus the Python program was written to implement priority-queue using array implementation of
binary heap and executed successfully.
61
EX.NO.:12(A) DATE:

GRAPH TRAVERSAL – DEPTH FIRST SEARCH

AIM
To write a Python program for implementing the traversal algorithm for Depth first traversal.

ALGORITHM
1. Start from any vertex, say Vi .
2. Vi is visited and then all vertices adjacent to Vi are traversed recursively using DFS.
3. Since, a graph can have cycles. We must avoid revisiting a node. To do this, when we
visit a vertex V, we mark it visited.
4. A node that has already been marked as visited should not be selected for traversal.
5. Marking of visited vertices can be done with the help of a global array visited[ ].
6. Array visited[ ] is initialized to false (0)

PROGRAM
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def DFSUtil(self, v, visited):
visited.add(v)
print(v, end=' ')
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)
def DFS(self, v):
visited = set()
self.DFSUtil(v, visited)
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)

62
g.addEdge(3, 3)
print("Following is DFS from (starting from vertex 2)")
g.DFS(2)

OUTPUT
Following is DFS from (starting from vertex 2)
2013

RESULT
Thus the Python program has been written for implementing the traversal algorithm for Depth
first traversal and executed successfully.

63
EX.NO.:12(B) DATE:

GRAPH TRAVERSAL – BREADTH FIRST SEARCH

AIM
To write a Python program for implementing the traversal algorithm for Breadth first traversal.

ALGORITHM
1. Start from any vertex, say Vi .
2. Vi is visited and then all vertices adjacent to Vi are traversed recursively using BFS.
3. avoid revisiting a node. To do this, when we visit a vertex V, we mark it visited.
4. A node that has already been marked as visited should not be selected for traversal.
5. Marking of visited vertices can be done with the help of a global array visited [ ].
6. Array visited [ ] is initialized to false (0).

PROGRAM
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def BFS(self, s):
visited = [False] * (max(self.graph) + 1)
queue = []
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0)
print (s, end = " ")
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)

64
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print ("Following is Breadth First Traversal")
print( " (starting from vertex 2)")
g.BFS(2)

OUTPUT
Following is Breadth First Traversal
(starting from vertex 2)
2031

RESULT
Thus the Python program has been written for implementing the traversal algorithm for Breadth
first traversal and executed successfully.
65
EX.NO.:13 DATE:

IMPLEMENTATION OFSINGLE SOURCE SHORTEST PATH ALGORITHM

AIM
To write a Python program to implement the shortest path using Dijkstra’s algorithm.

ALGORITHM
1. Select the source node also called the initial node
2. Define an empty set N that will be used to hold nodes to which a shortest path has been
found.
3. Label the initial node with , and insert it into N.
4. Repeat Steps 5 to 7 until the destination node is in N or there are no more labelled
nodes in N.
5. Consider each node that is not in N and is connected by an edge from the newly inserted
node.
6. (a) If the node that is not in N has no label then SET the label of the node = the label of
the newly inserted node + the length of the edge.
(b) Else if the node that is not in N was already labelled, then SET its new label = minimum
7. Pick a node not in N that has the smallest label assigned to it and add it to N.

PROGRAM
import sys
from heapq import heappop, heappush
class Edge:
def __init__(self, source, dest, weight):
self.source = source
self.dest = dest
self.weight = weight
class Node:
def __init__(self, vertex, weight):
self.vertex = vertex
self.weight = weight
def __lt__(self, other):
return self.weight < other.weight
class Graph:
def __init__(self, edges, N):
self.adj = [[] for _ in range(N)]

66
for edge in edges:
self.adj[edge.source].append(edge)
def get_route(prev, i, route):
if i >= 0:
get_route(prev, prev[i], route)
route.append(i)
def findShortestPaths(graph, source, N):
pq = []
heappush(pq, Node(source, 0))
dist = [sys.maxsize] * N
dist[source] = 0
done = [False] * N
done[source] = True
prev = [-1] * N
route = []
while pq:
node = heappop(pq)
u = node.vertex
for edge in graph.adj[u]:
v = edge.dest
weight = edge.weight
if not done[v] and (dist[u] + weight) < dist[v]:
dist[v] = dist[u] + weight
prev[v] = u
heappush(pq, Node(v, dist[v]))
done[u] = True
for i in range(1, N):
if i != source and dist[i] != sys.maxsize:
get_route(prev, i, route)
print(f"Path ({source} —> {i}): Minimum cost = {dist[i]}, Route ={route}")
route.clear()
if __name__ == '__main__':
edges = [Edge(0, 1, 10), Edge(0, 4, 3), Edge(1, 2, 2),
Edge(1, 4, 4), Edge(2, 3, 9), Edge(3, 2, 7),
Edge(4, 1, 1), Edge(4, 2, 8), Edge(4, 3, 2)]
N=5
graph = Graph(edges, N)
source = 0

67
findShortestPaths(graph, source, N)

OUTPUT
Path (0 —> 1): Minimum cost = 4, Route =[0, 4, 1]
Path (0 —> 2): Minimum cost = 6, Route =[0, 4, 1, 2]
Path (0 —> 3): Minimum cost = 5, Route =[0, 4, 3]
Path (0 —> 4): Minimum cost = 3, Route =[0, 4]

RESULT
Thus the Python program has been written to implement the shortest path using Dijkstra’s
algorithm and executed successfully.

68
EX.NO.:14(A) DATE:

IMPLEMENTATION OF MINIMUM SPANING TREE ALGORITHM

KRUSAL'S ALGORITHM

AIM
To write a Python program to implement the minimum spanning tree using Krusal’s algorithm.

ALGORITHM
1. Create classes for Graph and Vertex.

2. Create a function mst_krusal that takes a Graph object g as argument.

3. The function will return a Graph object which is a minimum spanning tree of the graph g.

4. An empty graph called mst is created which will hold a MST of the graph g.

5. The algorithm works by first sorting all the edges of g in ascending order by weight.

6. Then the smallest edge is taken from the sorted list.

7. If that edge does not form a cycle when added to mst, it is added.

8. Then the next smallest edge is taken and step 7 is performed again.

9. The above is performed until mst has the same number of vertices as g.

10. To determine whether adding an edge will form a cycle, each vertex in g is assigned a
component.

11. When any vertex is added to the MST, its component is updated.

12. If both vertices of an edge belong to the same component, then adding the edge will form

a cycle

PROGRAM
class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}

def add_vertex(self, key):


"""Add a vertex with the given key to the graph."""

69
vertex = Vertex(key)
self.vertices[key] = vertex

def get_vertex(self, key):


"""Return vertex object with the corresponding key."""
return self.vertices[key]

def __contains__(self, key):


return key in self.vertices

def add_edge(self, src_key, dest_key, weight=1):


"""Add edge from src_key to dest_key with given weight."""
self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)

def does_vertex_exist(self, key):


return key in self.vertices

def does_edge_exist(self, src_key, dest_key):


"""Return True if there is an edge from src_key to dest_key."""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])

def display(self):
print('Vertices: ', end='')
for v in self:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in self:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),dest.get_key(), w))

def __len__(self):
return len(self.vertices)

def __iter__(self):
return iter(self.vertices.values())

70
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

def get_key(self):
"""Return key corresponding to this vertex object."""
return self.key

def add_neighbour(self, dest, weight):


"""Make this vertex point to dest with given edge weight."""
self.points_to[dest] = weight

def get_neighbours(self):
"""Return all vertices pointed to by this vertex."""
return self.points_to.keys()

def get_weight(self, dest):


"""Get weight of edge from this vertex to dest."""
return self.points_to[dest]

def does_it_point_to(self, dest):


"""Return True if this vertex points to dest."""
return dest in self.points_to

def mst_krusal(g):
"""Return a minimum cost spanning tree of the connected graph g."""
mst = Graph() # create new Graph object to hold the MST

if len(g) == 1:
u = next(iter(g)) # get the single vertex
mst.add_vertex(u.get_key()) # add a copy of it to mst
return mst

# get all the edges in a list

71
edges = []
for v in g:
for n in v.get_neighbours():
# avoid adding two edges for each edge of the undirected graph
if v.get_key() < n.get_key():
edges.append((v, n))

# sort edges
edges.sort(key=lambda edge: edge[0].get_weight(edge[1]))

# initially, each vertex is in its own component


component = {}
for i, v in enumerate(g):
component[v] = i

# next edge to try


edge_index = 0

# loop until mst has the same number of vertices as g


while len(mst) < len(g):
u, v = edges[edge_index]
edge_index += 1

# if adding edge (u, v) will not form a cycle


if component[u] != component[v]:

# add to mst
if not mst.does_vertex_exist(u.get_key()):
mst.add_vertex(u.get_key())
if not mst.does_vertex_exist(v.get_key()):
mst.add_vertex(v.get_key())
mst.add_edge(u.get_key(), v.get_key(), u.get_weight(v))
mst.add_edge(v.get_key(), u.get_key(), u.get_weight(v))

# merge components of u and v


for w in g:
if component[w] == component[v]:
component[w] = component[u]

72
return mst

g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> <weight>')
print('mst')
print('display')
print('quit')

while True:
do = input('What would you like to do? ').split()

operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
weight = int(do[4])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest, weight)
g.add_edge(dest, src, weight)
else:

73
print('Edge already exists.')

elif operation == 'mst':


mst = mst_krusal(g)
print('Minimum Spanning Tree:')
mst.display()
print()

elif operation == 'display':


g.display()
print()

elif operation == 'quit':


break

OUTPUT
Undirected Graph
Menu
add vertex <key>
add edge <src> <dest> <weight>
mst
display
quit
What would you like to do? add vertex 1
What would you like to do? add vertex 2
What would you like to do? add vertex 3
What would you like to do? add vertex 4
What would you like to do? add vertex 5
What would you like to do? add vertex 6
What would you like to do? add edge 1 2 10
What would you like to do? add edge 1 5 30
What would you like to do? add edge 1 4 40
What would you like to do? add edge 2 5 20
What would you like to do? add edge 4 5 40
What would you like to do? add edge 5 3 40
What would you like to do? add edge 5 6 70
What would you like to do? add edge 3 6 50
What would you like to do? mst

74
Minimum Spanning Tree:
Vertices: 1 2 5 4 3 6
Edges:
(src=1, dest=2, weight=10)
(src=1, dest=4, weight=40)
(src=2, dest=1, weight=10)
(src=2, dest=5, weight=20)
(src=5, dest=2, weight=20)
(src=5, dest=3, weight=40)
(src=4, dest=1, weight=40)
(src=3, dest=5, weight=40)
(src=3, dest=6, weight=50)
(src=6, dest=3, weight=50)

What would you like to do? Quit

RESULT
Thus the Python program has been written to implement the minimum spanning tree using
Krusal’s algorithm and executed successfully
75
EX.NO.:14(B) DATE:

IMPLEMENTATION OF MINIMUM SPANING TREE ALGORITHM

PRIM’S ALGORITHM

AIM
To write a Python program to implement the minimum spanning tree using Prim’s algorithm.

ALGORITHM
1. Create a dictionary (to be used as a priority queue) PQ to hold pairs of ( node, cost ).
2. Push [ S, 0 ] ( node, cost ) in the dictionary PQ i.e Cost of reaching vertex S from source node
S is zero.
3. While PQ contains ( V, C ) pairs :
4. Get the adjacent node V ( key ) with the smallest edge cost ( value ) from the dictionary PQ.
5. Cost C = PQ [ V ]
6. Delete the key-value pair ( V, C ) from the dictionary PQ.
7. If the adjacent node V is not added to the spanning tree.
8. Add node V to the spanning tree.
9. Cost of the spanning tree += Cost C
10. For all vertices adjacent to vertex V not added to spanning tree.
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

76
# reaching the node from the source.
# 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

def main() :

g1_edges_from_node = {}

# Outgoing edges from the node: (adjacent_node, cost) in graph 1.

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

if __name__ == "__main__" :
main()

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

78
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
Thus the Python program has been written to implement the minimum spanning tree using Prim’s
algorithm and executed successfully

79

You might also like