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

AGNI COLLEGE OF TECHNOLOGY

(Approved by AICTE & Affiliated to Anna University)

Off Old Mahabalipuram Road, Thalambur, Chennai – 600 130

B-Tech – IT

II YEAR – III SEMESTER

CD3281-Data Structures and Algorithms Laboratory

LAB MANUAL

DEPARTMENT OF INFORMATION TECHNOLOGY


TABLE OF CONTENTS

S. NO DATE NAME OF THE EXPERIMENT PAGE NO SIGNATURE

1 IMPLEMENTATION OF SIMPLE ADTS AS


PYTHON CLASSES

2 (A) IMPLEMENTATION OF RECURSIVE


ALGORITHM FOR FINDING FACTORIAL
OF A NUMBER

2 (B) IMPLEMENTATION OF RECURSIVE


ALGORITHM FOR GENERATING
FIBONACCI SERIES

3 IMPLEMENTATION OF LIST ADT USING


PYTHON ARRAYS

4 (A) IMPLEMENTATION OF SINGLY LINKED


LIST

4 (B) IMPLEMENTATION OF CIRCULARLY


LINKED LIST

4 (C) IMPLEMENTATION OF DOUBLY LINKED


LIST

5 (A) IMPLEMENTATION OF STACK ADT


USING ARRAY

5 (B) IMPLEMENTATION OF STACK ADT


USING LINKED LIST

5 (C) IMPLEMENTATION OF QUEUE ADT


USING ARRAY

5 (D) IMPLEMENTATION OF QUEUE ADT


USING LINKED LIST

6 (A) IMPLEMENT AN APPLICATION OF


LINKED LIST USING PYTHON

6 (B) IMPLEMENT AN APPLICATION OF


STACK ADT USING PYTHON

6 (C) IMPLEMENT AN APPLICATION OF


QUEUE ADT USING PYTHON

7 (A) IMPLEMENTATION OF BUBBLE SORT


USING PYTHON

7 (B) IMPLEMENTATION OF SELECTION SORT


USING PYTHON
7 (C) IMPLEMENTATION OF INSERTION SORT
USING PYTHON

7 (D) IMPLEMENTATION OF MERGE SORT


USING PYTHON

7 (E) IMPLEMENTATION OF QUICK SORT


USING PYTHON

7 (F) IMPLEMENTATION OF LINEAR SEARCH


USING PYTHON

7 (G) IMPLEMENTATION OF BINARY SEARCH


USING PYTHON

8 IMPLEMENTATION OF HASH TABLES

9 IMPLEMENTATION OF TREE
REPRESENTATION AND TRAVERSAL
ALGORITHMS

10 IMPLEMENTATION OF BINARY SEARCH


TREE

11 IMPLEMENTATION OF HEAPS

12 GRAPH REPRESENTATION AND


TRAVERSAL ALGORITHMS

13 IMPLEMENTATION OF SINGLE SOURCE


SHORTEST PATH ALGORITHM

14 IMPLEMENTATION OF MINIMUM
SPANNING TREE ALGORITHMS
SYLLUBUS
Course Objective:

• To implement ADTs 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
List of Experiments:
1. Implement simple ADTs as Python classes
2. Implement recursive algorithms in Python
3. Implement List ADT using Python arrays
4. Linked list implementations of List
5. Implementation of Stack and Queue ADTs
6. Applications of List, Stack and Queue ADTs
7. Implementation of sorting and searching algorithms
8. Implementation of Hash tables
9. Tree representation and traversal algorithms
10. Implementation of Binary Search Trees
11. Implementation of Heaps
12. Graph representation and Traversal algorithms
13. Implementation of single source shortest path algorithm
14. Implementation of minimum spanning tree algorithms
Course Outcome:
At the end of the course, the student should be able to:
• implement ADTs as Python classes
• design, implement, and analyse linear data structures, such as lists, queues, and stacks,
according to the needs of different applications
• design, implement, and analyse efficient tree structures to meet requirements such as
searching, indexing, and sorting
• model problems as graph problems and implement efficient graph algorithms to solve
them
Text Books:

1. Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser, “Data


Structures and Algorithms in Python” (An Indian Adaptation), Wiley, 2021.
2. Lee, Kent D., Hubbard, Steve, “Data Structures and Algorithms with Python”
Springer Edition 2015.
3. Narasimha Karumanchi, “Data Structures and Algorithmic Thinking with
Python” Careermonk, 2015.

References:

1. Rance D. Necaise, “Data Structures and Algorithms Using Python”, John Wiley
and Sons, 2011.
2. Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein,
“Introduction to Algorithms”, Third Edition, PHI Learning, 2010.
3. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C++”, Fourth
Edition, Pearson Education,2014
4. Aho, Hopcroft, and Ullman, “Data Structures and Algorithms”, Pearson
Education India, 2002.
EX. NO: 1
IMPLEMENTATION OF SIMPLE ADTS AS PYTHON
DATE: CLASSES

AIM:
To implement a simple Abstract Data Type as a python class.
ALGORITHM:
1. Start
2. Create a class named student with data members rollno, name, course and member
function named display
3. Instantiate the class student with object s1 and s2
4. During instantiation pass the arguments for the data members through the constructor
5. Call display function to print the attributes for both objects s1 and s2
6. Stop
PROGRAM:
class student:
def init (self,rollno,name,course)
: self.rollno = rollno
self.name = name
self.course = course
def display(self):
print("my Roll Number is "+str(self.rollno))
print("my Name is "+str(self.name))
print("my Course is "+str(self.course))
s1 = student(101,"John","AI&DS")
s1.display()
s2 = student(102,"Raj","CSBS")
s2.display()
OUTPUT:
my Roll Number is 101
my Name is John
my Course is AI&DS
my Roll Number is 102
my Name is Raj
my Course is CSBS

RESULT:
Thus the program of Simple ADT is executed and the output is obtained successfully.
EX. NO: 2 (A) IMPLEMENTATION OF RECURSIVE ALGORITHM
FOR FINDING FACTORIAL OF A NUMBER
DATE:

AIM:
To implement a recursive algorithm for factorial of a number using python
ALGORITHM:
1. Start
2. Pass the number as an argument to a recursive factorial function.
3. Define the base condition as the number to be lesser than or equal to 1 and return 1 if
it is.
4. Otherwise call the function recursively with the number minus 1 multiplied by the
number itself.
5. Then return the result and print the factorial of the number.
6. Stop
PROGRAM:
# Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

OUTPUT:
The factorial of 7 is 5040

RESULT:
Thus the program of a recursive algorithm is executed and the output is obtained successfully.
EX. NO: 2 (B) IMPLEMENTATION OF RECURSIVE ALGORITHM
FOR GENERATING FIBONACCI SERIES
DATE:

AIM:
To implement a recursive algorithm for generating Fibonacci series using python
ALGORITHM:
1. Firstly get the length of the Fibonacci series as input from the user and keep the variable.
2. Then send the length as parameter to a recursive method named recursive_fibonacci().
3. Then the function will check whether the length is lesser than or equal to1.
4. Its length is less or equal to 1 then returns immediately.
5. If it is greater and not equal then it will make two adjoining recursive calls with the
argument as the (length-1) and (length-2) to the recursive_fibonacci() function.
6. Then we call recursive function inside for loop which iterates length of the Fibonacci
series and print result.
PROGRAM:
# Recursive function
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms = 10
# check if the number of terms is valid
if n_terms <= 0:
print("Invalid input ! Please input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))

OUTPUT:
Fibonacci series:
0
1
1
2
3
5
8
13
21
34

RESULT:
Thus the program of a recursive algorithm is executed and the output is obtained successfully.
EX. NO: 3
IMPLEMENTATION OF LIST ADT USING PYTHON
DATE: ARRAYS

AIM:
To implement List ADT using Array package in python
ALGORITHM:
1. Start
2. Import the necessary package for implementation.
3. Define the array and specify the values.
Using the functions in the Array package that is insert; for inserting the values, remove for deleting
the specified index value, reverse function to reverse the array, and other such functions in array
package
4. Display the output of each functions.
5. Stop
PROGRAM:
# Importing Array module
import array
# Array creation
arr=array.array('i',[1,2,3])
print(arr)
# Appended a new item 4 at the end of the array
arr.append(4)
print(arr)
# inserted new element 5 at 2nd index position
arr.insert(2,5)
print(arr)
# removed the element at the end of the array
arr.pop()
print(arr)
# removed the item mentioned ar argument
arr.remove(2)
print(arr)
# Return the index position of the value mentioned as argument
print(arr.index(3))
# 5 is at index position 1
print(arr.index(5))
# used to reverse my array
arr.reverse()
print(arr)

OUTPUT:

RESULT:
Thus the program of List ADT is executed and the output is obtained successfully.
EX. NO: 4 (A)
IMPLEMENTATION OF SINGLY LINKED LIST
DATE:

AIM:
To implement a List using Singly Linked list in python
ALGORITHM:
1. Start
2. Creation: Get the number of elements, and create the nodes having structures DATA,
LINK and store the element in Data field, link them together to form a linked list.
3. Insertion: Get the number to be inserted and create a new node store the value in
DATA field. And insert the node in the required position.
4. Deletion: Get the number to be deleted. Search the list from the beginning and locate
the node then delete the node.
5. Display: Display all the nodes in the list.
6. Stop
PROGRAM:
# Class created for node creation
class Node:
def init (self,data):
self.data = data
self.next = None
#Linked List Class to perform LL operations
class LL:
def init (self):
self.head = None
# Function to display the linked list
def display(self):
temp = self.head
if self.head is None: # if head is none it means list is empty
print ("List is Empty")
while temp:
print(temp.data,"--->",end=" ")
temp = temp.next
# Function to Insert node at the beginning of the LL
def insert_begining(self,data):
nb = Node(data)
nb.next = self.head
self.head = nb
# Function to Insert node at the end of the LL
def insert_end(self,data):
ne = Node(data)
temp = self.head
while temp.next:
temp = temp.next
temp.next= ne # make temp's next postion as new node
# Function to Insert node at a specific position in the middle of the LL
def insert_position(self,pos,data):
np = Node(data) # create new node
temp = self.head
for i in range(pos-1): #loop till the specified position-1; i value starts from 0
temp = temp.next
np.data = data
np.next = temp.next
temp.next = np
# Function to Delete node at the beginning of the LL
def delete_beginning(self):
temp = self.head
self.head = temp.next
temp.next =None
# Function to delete node at the end of the LL
defdelete_end(self):
prev = self.head
temp =self.head.next
while temp.next is not None:
temp = temp.next
prev = prev.next
prev.next = None
# Function to delete node at a specified position in the LL
def delete_position(self,pos):
prev = self.head
temp = self.head.next
for i in range(pos-1):
temp = temp.next
prev = prev.next
prev.next =temp.next
#Object created for LL class
obj = LL()
# node 1 created with data 10 created
n1 = Node(10)
obj.head = n1
# node 2 created with data 20 created
n2 = Node(20)
n1.next = n2
# node 3 with data 30 created
n3 = Node(30)
n2.next = n3
# display the linked list created
print("DISPLAY THECREATEDLIST.......")
obj.display()
# Insertion of data 5 at the beginning of the list
obj.insert_begining(5)
print("AFTER INSERTING 5 ATTHEBEGINNING. .... ")
obj.display()
# Insert 40 at the end of the list
obj.insert_end(40)
print("INSERTING 40 AT THE END OF THE LIST")
obj.display()
# Insert data 25 at the 3rd position in the list
obj.insert_position(3,25)
print("INSERTING 25 AT THE MIDDLE OF THE LIST")
obj.display()
#function call for deletion at the beginning
obj.delete_beginning()
print("AFTER DELETING THE FIRST NODE 5 FROM THE LIST...")
obj.display()
# function call for deletion at the end of the LL
obj.delete_end()
print("AFTER DELETING THE LAST NODE 40 FROM THE LIST...")
obj.display()
# Function call for deletion at the location 1, where the index position of this LL is started
from 0
obj.delete_position(1)
print("AFTER DELETING MIDDLE NODE 25 FROM THE LIST...")
obj.display()
OUTPUT:
DISPLAY THE CREATED LIST....
10 ---> 20 ---> 30 --->
INSERTING 5 AT THE BEGINNING....
5 ---> 10 ---> 20 ---> 30 --->
INSERTING 40 AT THE END OF THE LIST
5 ---> 10 ---> 20 ---> 30--->40 ---- >
INSERTING 25 AT THE MIDDLE OF THE LIST
5 ---> 10 ---> 20 ---> 25 ---> 30--->40 ---- >
AFTER DELETING THE FIRST NODE 5 FROM THE LIST...
10 ---> 20 ---> 25 ---> 30 ---> 40 --->
AFTER DELETING THE LAST NODE 40 FROM THE LIST...
10 ---> 20 ---> 25 ---> 30 --->
AFTER DELETING MIDDLE NODE 25 FROM THE LIST...
10 ---> 25 ---> 30 --->

RESULT:
Thus the program of Singly Linked List is executed and the output is obtained successfully.
EX. NO: 4 (B)
AIM: IMPLEMENTATION OF CIRCULARLY LINKED
DATE: LIST
AIM:
To write a python program to implement circular linked list
ALGORITHM:
1. Define a Node class which represents a node in the list. It has two properties data and
next which will point to the next node.
2. Define another class for creating the circular linked list, and it has two nodes:head and
tail. It has two methods: add() and display().
3. add() will add the node to the list:

i. It first checks whether the head is null, then it will insert the node as the
head.
ii. Both head and tail will point to the newly added node.
iii. If the head is not null, the new node will be the new tail, and the new tail
will point to the head as it is a circular linked list.
4. delete() will delete the mode from the list:
i. specify the position to be deleted if in case of middle element
ii. beginning: move the head pointer to the next element and change the next
address of tail to current head
iii. end: move tail to the before element and change next of tail to the head
5. display() will show all the nodes present in the list.
i. Define a new node 'n' that will point to the head.
ii. Print n.data till n will points to head
iii. n will point to the next node in the list in each iteration.

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
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 \n Enter 2 to delete the
last element \n Enter 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:
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:
returnTrue
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")
obj = CSLL()
while True:
option = int(input("Enter 1 to add an element\n Enter 2 to delete an element\n Enter 3
to clear the Linked " "List\n Enter 4 to display the Linked List\n Enter 5 to exit ::"))

if option == 1:

value = int(input("Enter the value you want to add ::"))


obj.add(value)
continue
elif option == 2:
obj.delete()
continue
elif option == 3:
obj.clear()
continue
elif option == 4:
obj.display()
continue
elif option == 5:
print("Goodbye")
break
elif option == 6:
print(obj.empty())
else:
print("Wrong option")

OUTPUT:

RESULT:
Thus the program of Circularly Linked List is executed and the output is obtained
successfully.
EX. NO: 4 (C)
IMPLEMENTATION OF DOUBLY LINKED LIST
DATE:

AIM:
To write a python program for implementing Doubly linked list
ALGORITHM:
1. Define a Node class which represents a node in the list. It will have three properties:
data, previous which will point to the previous node and next which will point to the
next node.
2. Define another class for creating a doubly linked list, and it has two nodes: head and
tail. Initially, head and tail will point to null.
3. Insertion occurs in three cases at the beginning, end and middle of the list
i. For insertion in the beginning, create a new node, make the next pointer
of the new node to point to the head and make the new node as present
head
ii. For insertion at the end, create a new node, make the previous pointer
of the new node to point to the tail and make new node as the tail
iii. For insertion at a specified position, traverse a pointer till the specified
position – 1 location and update the pointers.
4. Deletion as well occurs in three cases at the beginning, end and middle of the list

i. For deletion at the beginning, assign a new pointer to head named temp,
and move head to point to the next node, then make temp’s next pointer
as none
ii. For deletion at the end of the list, assign new variable temp to accessthe
last node that is tail , move tail to the previous node and then make temp’s
previous pointer as none
iii. For deletion at the middle of the list, move two pointers for traversing
till the position-1 and position+1 respectively and then update the
pointers.
5. display() will show all the nodes present in the list.
i. Define a new node 'temp' that will point to the head.
ii. Print temp. data till current points to null.
iii. Temp will point to the next node in the list in each iteration.

PROGRAM:
class Node:
def init (self,data):
self.data = data
self.prev = None
self.next = None
class DLL:
def init (self):
self.head = None
# Function to display the Doubly Linked list
def display(self):
if self.head is None:
print("Empty Doubly Linked List")
else:
temp = self.head
while temp:
print(temp.data,"--->",end=" ")
temp = temp.next
def insert_beginning(self,data):
n = Node (data) # create new node n
temp = self.head # Assign head to temp variable
temp.prev=n # set temp's previous field to new node n
n.next= temp # set new node's next totemp
self.head=n # Assign head to n
definsert_end(self,data):
n=Node(data) # create new node n
temp=self.head # Assign head to temp
while temp.next is not None: # loop till temp.next is not None
temp=temp.next # set temp to temp.next
temp.next= n # Assign temp's next to new node n
n.prev=temp # Assign temp to n's previousfield
def insert_position(self,pos,data):
n=Node(data) # create noden
temp=self.head # Assign head to temp
for iin range(1,pos-1): # loop from 1 to the specified position-1
temp=temp.next # set temp.next as temp
n.prev=temp # Assign temp as n's previous field
n.next= temp.next # set temp's next as new node n's next
temp.next.prev=n # Assign new node n as previous oftemp.next
temp.next= n # set n as temp's next field
defdelete_beginning(self):
temp = self.head
self.head = temp.next
temp.next = None
self.head.prev = None
def delete_end(self):
temp = self.head.next
before = self.head
while temp.next is not None:
temp = temp.next
before = before.next
before.next = None
temp.prev =None
def delete_position(self,pos):
temp = self.head.next
before =self.head
for i in range(1,pos-1):
temp = temp.next
before = before.next
before.next = temp.next
temp.next.prev = before
temp.next = None
temp.prev = None
obj = DLL() # create object for DLL class
n1 = Node(10) # create new node n1 with data 10
obj.head = n1 # set n1 as head
n2 = Node(20) # create new node n2 with data 20
n2.prev = n1 # set n2's previous field to n1
n1.next = n2 # set n1's next field to n2
n3 = Node(30) # create new node n3 with data 30
n3.prev = n2 # set n3's previous field as n2
n2.next = n3 # set n2's next field as n3
n4 = Node(40) # create new node n4 with data 40
n4.prev = n3 # set n4's previous field as n3
n3.next = n4 # set n3's next field as n4
print("Created doubly linked list...")
obj.display()
obj.insert_beginning(5)
print("After inserting 5 at the beginning of doubly linked list...")
obj.display()
obj.insert_end(50)
print("After inserting 50 at the end of doubly linked list...")
obj.display()
obj.insert_position(4,25)
print("After inserting 25 as 4th item of doubly linked list...")
obj.display()
obj.delete_beginning()
print("Deletion at the beginning...")
obj.display()
obj.delete_end()
print("Deletion at the end of doubly linked list...")
obj.display()
obj.delete_position(3)
print("Deleting the 3rd item from doubly linked list...")
obj.display()
OUTPUT:
Created doubly linked list...
10 ---> 20 ---> 30 ---> 40 --->
After inserting 5 at the beginning of doubly linked list...
5 ---> 10 ---> 20 ---> 30 ---> 40 --->
After inserting 50 at the end of doubly linked list...
5 ---> 10 ---> 20 ---> 30 ---> 40 ---> 50 --->
After inserting 25 as 4th item of doubly linked list...
5 ---> 10 ---> 20 ---> 25 ---> 30 ---> 40 ---> 50 --->
Deletion at the beginning...
10 ---> 20 ---> 25 ---> 30 ---> 40 ---> 50 --->
Deletion at the end of doubly linked list...
10 ---> 20 --->25 ---> 30 ---> 40 --->
Deleting the 3rd item from doubly linked list...
10 ---> 20 ---> 30 ---> 40 --->

RESULT:
Thus the program of Doubly Linked List is executed and the output is obtained successfully.
EX. NO: 5 (A)
IMPLEMENTATION OF STACK ADT USING
DATE: ARRAY

AIM:
To write a python program for implementing stack ADT using array.
ALGORITHM:
1. Start
2. Initialize top = -1
3. Push operation increases top by one and writes pushed element to storage[top]
4. Pop operation checks that top is not equal to -1 and decreases top variable by1
5. Display operation checks that top is not equal to -1 and returns storage[top]
6. Stop
PROGRAM:
Class StackUsingArray:
def init (self):
self.stack = []

#Method to append the element in the stack at top position.


def push(self, element):
self.stack.append(element)
#Method to Pop last element from the top of the stack
def pop(self):
if(not self.isEmpty()):
lastElement = self.stack[-1] #Save the last element to return
del(self.stack[-1]) #Remove the last element
return lastElement
else:
return("Stack Already Empty")
#Method to check if stack is empty or not
def isEmpty(self):
return self.stack == []
def printStack(self):
print(self.stack)
#Main code
if name == "main":

s = StackUsingArray()
print("*"*5+" Stack Using Array"+5*"*")
while(True):
el = int(input("1 for Push \n2 for Pop \n3 to check if it is Empty \n4 to print Stack \n5
to exit \n"))
if(el == 1):
item = input("Enter Element to push in stack\n")
s.push(item)
if(el == 2):
print(s.pop())
if(el == 3):
print(s.isEmpty())
if(el == 4):
s.printStack()
if(el == 5):
break
OUTPUT:
RESULT:

Thus the program of Stack ADT using Array is executed and the output is obtained
successfully.
EX. NO: 5 (B)
IMPLEMENTATION OF STACK ADT USING LINKED
DATE: LIST

AIM:
To write a python program to implement Stack ADT using Linked list
ALGORITHM:
1. Start
2. Push operation inserts an element at the front.
3. Pop operation deletes an element at the front of the list
4. Display operation displays all the elements in the list.
5. Stop
PROGRAM:
class Node:
# Class to create nodes of linked list
# Constructor initializes node automatically
def init (self,data):
self.data = data
self.next = None
class Stack:
# head is default NULL
def init (self):
self.head = None
# Checks if stack is empty
def isempty(self):
if self.head == None:
return True
else:
return False
# Method to add data to the stack
# adds to the start of the stack
defpush(self,data):
if self.head == None:
self.head=Node(data)
else:
newnode = Node(data)
newnode.next = self.head
self.head = newnode
# Remove element that is the current head (start of the stack)
def pop(self):
if self.isempty():
return None
else:
# Removes the head node and makes
#the preceding one the new head
poppednode = self.head
self.head = self.head.next
poppednode.next = None
return poppednode.data
# Returns the head node data
def top(self):
if self.isempty():
return None
else:
return self.head.data
# Prints out the stack
def display(self):
iternode = self.head
if self.isempty():
print("Stack Underflow")
else:
while(iternode != None):
print(iternode.data,"->",end = " ")
iternode = iternode.next
return
# Driver code
MyStack = Stack()
MyStack.push(10)
MyStack.push(20)
MyStack.push(30)
MyStack.push(40)
# Display stack elements
MyStack.display()
# Print top element of stack
print("\nTop element is ",MyStack.top())
# Delete top elements of stack
MyStack.pop()
MyStack.pop()
# Display stack elements
MyStack.display()
# Print top element of stack
print("\nTop element is ", MyStack.top())

OUTPUT:
40 -> 30 -> 20 -> 10 ->
Top element is 40
20 -> 10 ->
Top element is20

RESULT:
Thus the program of Stack ADT using Linked list is executed and the output is obtained
successfully.
EX. NO: 5 (C)
IMPLEMENTATION OF QUEUE ADT USING
DATE: ARRAY

AIM:
To implement Queue ADT using Array in python
ALGORITHM:
1. Start
2. Initialize front=0; rear= -1.
3. Enqueue operation moves a rear by one position and inserts a element at the rear.
4. Dequeue operation deletes a element at the front of the list and moves the front by one
Position.
5. Display operation displays all the element in the list.
6. Stop
PROGRAM:
# Implement Queue using List (Functions)
q=[]
def Enqueue():
if len(q)==size: # check we there the stack is full or
not print("Queue is Full!!!!")
else:
element=input("Enter the element:")
q.append(element)
print(element,"is added to the Queue!")
def dequeue():
if not q:# or if len(stack)==0
print("Queue is Empty!!!")
else:
e=q.pop(0)
print("element removed!!:",e)
def display():
print(q)
size=int(input("Enter the size of Queue:"))
while True:
print("Select the Operation:1.Add 2.Delete 3. Display 4. Quit")
choice = int(input())
if choice==1:
Enqueue()
elif choice==2:
dequeue()
elif choice==3:
display()
elif choice==4:
break
else:
print("Invalid Option!!!")
OUTPUT:

RESULT:
Thus the program of Queue ADT using Array is executed and the output is obtained
successfully.
EX. NO: 5 (D)
IMPLEMENTATION OF QUEUE ADT USING LINKED
DATE: LIST

AIM:
To implement a Queue ADT using Linked list in python
PROCEDURE:
1. Start
2. Enqueue operation inserts an element at the rear of the list.
3. Dequeue operation deletes an element at the front of the list.
4. Display operation display all the element in the list.
5. Stop
PROGRAM:
class Node:
def init (self,data):
self.data = data
self.next = None
class Queue:
def init (self):
self.head =None
def display(self):
temp =self.head
print('Queue is:[', end='')
while temp:
print(temp.data, end=", ")
temp = temp.next
print(']')
def enqueue(self, data):
if self.head is None:
self.head = Node(data)
else:
temp = self.head
while temp.next is not None:

temp = temp.next
temp.next = Node(data) self.display()
def dequeue(self):
if self.head is None:
print('Queue is Empty')
self.display()
return None
else:
data=self.head.data
self.head=self.head.next
self.display()
return data
def main():
Q = Queue()
print('1.enqueue\n2.dequeue\n3.exit')
while 1:
choice = input('Enter your option:')
if choice is '1':
d = int(input('Enter data:'))
Q.enqueue(d)
elif choice is'2':
print('Deleted element is:',Q.dequeue())
else:
break
if name == 'main':
main()
OUTPUT:

RESULT:
Thus the program of Queue ADT using Linked list is executed and the output is obtained
successfully.
EX. NO: 6 (A)
IMPLEMENT AN APPLICATION OF LINKED LIST
DATE: USING PYTHON
AIM:
To implement an application for Linked list to add two polynomials using linked list
ALGORITHM:

1. Loop around all values of linked list and follow step 2&3.
2. if the value of a node’s exponent. is greater copy this node to result node and head
towards the next node.
3. if the values of both node’s exponent is same add the coefficients and then copy the
added value with node to the result.
4. Print the resultant node.

PROGRAM:
# Add two polynomials using linked list
class Node:
def init (self, data, power) :
self.data = data
self.power = power
self.next = None
# Update node value
def updateRecord(self, data, power) :
self.data = data
self.power = power
class AddPolynomial :
def init (self) :
self.head = None
# Display given polynomial nodes
def display(self) :
if (self.head == None) :
print("Empty Polynomial ")
print(" ", end = "")
temp = self.head
while (temp != None) :
if (temp != self.head):
print("+", temp.data, end = "")
else :
print(temp.data, end = "")
if (temp.power != 0) :
print("x^", temp.power, end = " ",sep = "")
# Visit to next node
temp = temp.next
print(end = "\n")
# Add node with given data and power
def addNode(self, data, power) :
if (self.head == None) :
# Add first node
self.head = Node(data, power)
else :
node = None
temp = self.head
location = None
# Find the valid new node location
while (temp != None and temp.power >= power) :
location = temp
temp = temp.next
if (location != None and location.power == power) :
# When polynomial power already exists
# Then add current add to previous data
location.data = location.data + data
else :
node = Node(data, power)
if (location == None) :
# When add node in begining
node.next = self.head
self.head = node
else :
# When adding node in intermediate
# location or end location
node.next = location.next
location.next = node
# Add two polynomial
def addTwoPolynomials(self, other) :
# Define some useful variable
result = None
tail = None
node = None
# Get first node of polynomial
first = self.head
second = other.head
# Execute loop until when polynomial are exist
# And add two polynomial.
# Process takes O(n) time.
while (first != None or second != None) :
# Create node with default value
node = Node(0, 0)
if (result == None):
# When first resultant node
result = node
if (first != None and second != None) :
if (first.power == second.power) :
# When the polynomial node power are same
node.updateRecord(first.data + second.data, first.power)
first = first.next
second = second.next
elif (first.power > second.power) :
# When first polynomial power are larger
node.updateRecord(first.data, first.power)
first = first.next
else :
# When second polynomial power are larger
node.updateRecord(second.data, second.power)
second = second.next
elif (first != None) :
# When first polynomial are not empty
# Update the current node information
node.updateRecord(first.data, first.power)
first = first.next
else :
# When second polynomial are not empty
node.updateRecord(second.data, second.power)
second = second.next
if (tail == None) :
tail = node
else :
# Add new node at end of resultant polynomial
tail.next = node
tail = node
# return first node
return result
def main() :
poly1 = AddPolynomial()
poly2 = AddPolynomial()
result = AddPolynomial()
# Add node in polynomial poly1
poly1.addNode(9,3)
poly1.addNode(4,2)
poly1.addNode(3,0)
poly1.addNode(7,1)
poly1.addNode(3,4)
# Add node in polynomial poly2
poly2.addNode(7,3)
poly2.addNode(4,0)
poly2.addNode(6,1)
poly2.addNode(1,2)
# Display Polynomial nodes
print("\n Polynomial A")
poly1.display()
print(" Polynomial B")
poly2.display()
result.head = poly1.addTwoPolynomials(poly2)
# Display calculated result
print(" Result")
result.display()
ifname == "main":main()

OUTPUT:
Polynomial A
3x^4 + 9x^3 + 4x^2 + 7x^1 + 3
Polynomial B
7x^3 + 1x^2 + 6x^1 + 4
Result
3x^4 + 16x^3 + 5x^2 + 13x^1 + 7

RESULT:
Thus the program of Linked List using Python is executed and the output is obtained
successfully.
EX. NO: 6 (B)
IMPLEMENT AN APPLICATION OF STACK ADT
DATE: USING PYTHON

AIM:
To implement a python code to convert infix to postfix expression using Stack ADT
ALGORITHM:

1. Scan the Infix Expression from left to right.


2. If the scanned character is an operand, append it with final Infix to Postfix string.
3. Else,
i. If the precedence order of the scanned(incoming) operator is greater than the
precedence order of the operator in the stack (or the stack is empty or the
stack contains a ‘(‘ or ‘[‘ or ‘{‘), push it on stack.
ii. Else, Pop all the operators from the stack which are greater than or equal to
in precedence than that of the scanned operator. After doing that Push the
scanned operator to the stack. (If you encounter parenthesis while popping
then stop there and push the scanned operator in the stack).
4. If the scanned character is an ‘(‘ or ‘[‘ or ‘{‘, push it to the stack.
5. If the scanned character is an ‘)’or ‘]’ or ‘}’, pop the stack and output it until a ‘(‘ or
‘[‘ or ‘{‘ respectively is encountered, and discard both the parenthesis.
6. Repeat steps 2-6 until infix expression is scanned.
7. Print the output
8. Pop and output from the stack until it is not empty.

PROGRAM:
Operators = set(['+', '-', '*', '/', '(', ')', '^']) # collection of Operators
Priority = {'+':1, '-':1, '*':2, '/':2, '^':3} # dictionary having priorities of Operators
def infixToPostfix(expression):
stack = [] # initialization of empty stack
output = ‘’
for character in expression:
if character not in Operators: # if an operand append in postfix expression
output+= character
elif character=='(': # else Operators push onto stack
stack.append('(')
elif character==')':
while stack and stack[-1]!= '(':
output+=stack.pop()
stack.pop()
else:
while stack and stack[-1]!='(' and Priority[character]<=Priority[stack[-1]]:
output+=stack.pop()
stack.append(character)
while stack:
output+=stack.pop()
return output
expression = input('Enter infix expression ')
print('infix notation: ',expression)
print('postfix notation: ',infixToPostfix(expression))
OUTPUT:
Enter infix expression (A*B)-(C+D)+E
infix notation: (A*B)-(C+D)+E
postfix notation: AB*CD+-E+

RESULT:
Thus the program of Stack ADT using Python is executed and the output is obtained
successfully.
EX. NO: 6 (C)
IMPLEMENT AN APPLICATION OF QUEUE ADT
DATE: USING PYTHON

AIM:
To implement a multi process scheduling queue using python
ALGORITHM:

1. Use multiprocessing.queue to use a queue for multiprocessing


2. Call multiprocessing.Queue() to create a Queue to share between multiple
processes.
3. Call multiprocessing.Process(target=function, args=[queue]) to create a process to
execute function with arguments to the queue created in the previous step.
4. Set Process.daemon to True to run the process in the background.
5. Call Process.start() to start the process.
6. Call Process.join() to block execution until the Process has finished executing.

PROGRAM:
import multiprocessing
def consumer(queue):
while True:
msg = queue.get()
if (msg == 'DONE'):
break
def producer(count, queue):
for i in range(count):
queue.put(i)
queue.put('DONE')
queue = multiprocessing.Queue()
consumer_process = multiprocessing.Process(target=consumer, args=[queue])
consumer_process.daemon = True
consumer_process.start()
count = 10**4
producer(count, queue) #Send data to the queue
consumer_process.join()
print("Sent {0} numbers to Queue...".format(count))
OUTPUT:
Sent 10000 numbers to Queue...

RESULT:
Thus the program of Queue ADT using Python is executed and the output is obtained
successfully.
EX. NO: 7 (A)
IMPLEMENTATION OF BUBBLE SORT USING
DATE: PYTHON

AIM:
To implement bubble sort using python
ALGORITHM:
1. Get the total number of elements. Get the total number of items in the given array
2. Determine the number of outer passes (n – 1) to be done. Its length is array minus one
3. Perform inner passes (n – 1) times for outer pass 1. Get the first element value and
compare it with the second value. If the second value is less than the first value, then
swap the positions
4. Repeat step 3 passes until you reach the outer pass (n – 1). Get the next element in the
list then repeat the process that was performed in step 3 until all the values have been
placed in their correct ascending order.
5. Return the result when all passes have been done. Return the results of the sorted array

PROGRAM:
def bubbleSort(arr):
n =len(arr)
# Traverse through all array elements
for i in range(n-1):
# range(n) also work but outer loop will
# repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j + 1] :
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# Driver code to test above
arr = [64, 134, 25, 12, 56, 10, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("% d" % arr[i],end=" ")

OUTPUT:
Sorted array is:
10 12 25 56 64 90 134

RESULT:
Thus the program of Bubble sort using Python is executed and the output is obtained
successfully.
EX. NO: 7 (B)
IMPLEMENTATION OF SELECTION SORT
DATE: USING PYTHON
AIM:
To implement selection sort using python
ALGORITHM:
1. Get the value of n which is the total size of the array
2. Partition the list into sorted and unsorted sections. The sorted section is initially empty
while the unsorted section contains the entire list
3. Pick the minimum value from the un partitioned section and placed it into the sorted
section.
4. Repeat the process (n – 1) times until all of the elements in the list have been sorted.
5. Return the sorted list and print it.

PROGRAM:
def selectionSort( itemsList ):
n = len( itemsList )
for i in range( n - 1 ):
minValueIndex = i
for j in range( i + 1, n):
if itemsList[j] < itemsList[minValueIndex] :
minValueIndex = j
if minValueIndex != i :
temp = itemsList[i]
itemsList[i] = itemsList[minValueIndex]
itemsList[minValueIndex] = temp
return itemsList
el = [29,6,37,45,5]
print("Unsortedlist. ...")
print(el)
print("Sorted list")
print(selectionSort(el))
OUTPUT:
Unsorted list....
[29, 6, 37, 45, 5]
Sorted list
[5, 6, 29, 37, 45]

RESULT:
Thus the program of Selection sort using Python is executed and the output is obtained
successfully.
EX. NO: 7 (C)
IMPLEMENTATION OF INSERTION SORT USING
DATE: PYTHON
AIM:
To implement the insertion sort using python
ALGORITHM:
1. Create a function insetion_sort()
2. Declare a list.
3. Mark the first element assorted
4. Initialize for loop
5. Iterate each element and extract the locations.
6. Move sorted element right by 1
7. break the loop and insert the key here
8. Print the sorted Array

PROGRAM:
def insertion_sort(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=j-1
# Place key at after the element just smaller than it.
arr[j + 1] = key
arr = [9, 8, 6, 7, 1]
print("Unsorted Array:", arr)
insertion_sort(arr)
print('Sorted Array: ', arr)

OUTPUT:
Unsorted Array: [9, 8, 6, 7, 1]
Sorted Array: [1, 6, 7, 8, 9]

RESULT:
Thus the program of Insertion sort using Python is executed and the output is obtained
successfully.
EX. NO: 7 (D)
IMPLEMENTATION OF MERGE SORT USING
DATE: PYTHON

AIM:
To implement Merge sort using python
ALGORITHM:
1. Store the length of the list
2. List with length less than is already sorted
3. Identify the list midpoint and partition the list into a left_partition and a
right_partition
4. To ensure all partitions are broken down into their individual components, the
merge_sort function is called and a partitioned portion of the list is passed as a
parameter
5. The merge_sort function returns a list composed of a sorted left and right partition.
6. Takes in two lists and returns a sorted list made up of the content within the two lists
7. Initialize an empty list output that will be populated with sorted elements. Initialize
two variables i and j which are used pointers when iterating through the lists.
8. Executes the while loop if both pointers i and j are less than the length of the left and
right lists
9. Compare the elements at every position of both lists during each iteration
10. Move pointer to the right
11. The remnant elements are picked from the current pointer value to the end of the
respective list
PROGRAM:
def merge_sort(list):
list_length = len(list)
if list_length == 1:
return list
mid_point = list_length // 2
left_partition = merge_sort(list[:mid_point])
right_partition = merge_sort(list[mid_point:])
return merge(left_partition, right_partition)
def merge(left, right):
output = []
i=j=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
output.append(left[i])
i += 1
else:
output.append(right[j])
j += 1
output.extend(left[i:])
output.extend(right[j:])
return output
def run_merge_sort():
unsorted_list = [4, 7, 2, 61, 1, 1, 61, 44, 10, 33, 15, 7, 23]
print("Unsorted list...",unsorted_list)
sorted_list = merge_sort(unsorted_list)
print("Sorted list...",sorted_list)
run_merge_sort()

OUTPUT:
Unsorted list... [4, 7, 2, 61, 1, 1, 61, 44, 10, 33, 15, 7, 23]
Sorted list... [1, 1, 2, 4, 7, 7, 10, 15, 23, 33, 44, 61, 61]

RESULT:
Thus the program of Merge sort using Python is executed and the output is obtained
successfully.
EX. NO: 7 (E)
IMPLEMENTATION OF QUICK SORT USING
DATE: PYTHON

AIM:
To implement Quick sort in python
ALGORITHM:
1. Create a function partition()
2. Pass three parameters arr, low, high
3. Select rightmost element as pivot
4. declare pointer for greater element
5. traverse through all elements and compare them with pivot
6. If the smaller element is found swap them with pivot
7. Return the index position
8. Create a function Quicksort()
9. Pass three parameters arr, low, high
10. Find the pivot element
11. Do Recursive call on the left pivot and right pivot
12. The array is now sorted
13. Print the sorted array
PROGRAM:
def partition(arr, low, high):
i=(low-1) # index of smaller element
pivot=arr[high] # pivot
for j in range(low, high):
# If current element is smaller than or
# equal to pivot
if arr[j] <= pivot:
# increment index of smaller element
i =i+1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return(i+1)
# The main function that implements QuickSort
# arr[] --> Array to be sorted,
# low --> Starting index,
# high --> Ending index
# Function to do Quick sort
def quickSort(arr, low, high):
if len(arr) == 1:
return arr
if low < high:
# pi is partitioning index, arr[p] is now
# at right place
pi = partition(arr, low, high)
# Separately sort elements before
# partition and after partition
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
# Driver code to test above
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
print("Input arrat: ",arr)
quickSort(arr, 0, n-1)
print("Sorted array is:")
for i inrange(n):
print("%d" % arr[i])

OUTPUT:
Input arrat: [10, 7, 8, 9, 1, 5]
Sorted array is:
1
5
7
8
9
10

RESULT:
Thus the program of Quick sort using Python is executed and the output is obtained
successfully.
EX. NO: 7 (F)
IMPLEMENTATION OF LINEAR SEARCH USING
DATE: PYTHON

AIM:
To implement a python code to perform linear search
ALGORITHM:

1. Create a function linear_search()


2. Declare three parameters array, length of the array, and number to be found.
3. Initialize for loop
4. Iterate each element and compare the key value.
5. If the element is present return index
6. Else return not present

PROGRAM:
def linear_search(arr, a, b):
# Going through array
for i in range(0, a):
if (arr[i] == b):
return i
return -1
arr = [9, 7, 5, 3, 1]
print("The array given is ", arr)
b=5
print("Element to be found is ", b)
a = len(arr)
index = linear_search(arr, a, b)
if(index == -1):
print("Element is not in the list")
else:
print("Index of the element is: ", index)
OUTPUT:
The array given is [9, 7, 5, 3, 1]
Element to be found is5
Index of the element is:2

RESULT:
Thus the program of Linear Search using Python is executed and the output is obtained
successfully.
EX. NO: 7 (G)
IMPLEMENTATION OF BINARY SEARCH USING
DATE: PYTHON

AIM:
To write a python code for implementing Binary Search.
ALGORITHM:

1. Create a function binary_search() which accepts 4 parameters (array, low, high, a).
2. Declare two variables to store the highest and the lowest values in the list.
3. Then Follow step 4 until the lowest and highest meet each other:
4. mid = (low + high)/2 if (a == arr[mid]) return mid else if (a > arr[mid])
a is on the right side low = mid + 1else
a is on the left side high = mid - 1
5. Initialize the array and the element to be found
6. Print the resulting position if the element is found else print Not found.
PROGRAM:
def binary_search(arr, a, low, high):
# Repeat until low and high meet each other
while low <=high:
mid = low + (high - low)//2
if arr[mid] ==a:
return mid
elif array[mid] < a:
low = mid + 1
else:
high = mid - 1
return -1
arr = [1, 2, 3, 4, 5, 6, 7]
a=4
#printing the array
print("The given array is", arr)
#printing element to be found
print("Element to be found is ", a)
index = binary_search(arr, a, 0, len(arr)-1)
if index != -1:
print("The Index of the element is " + str(index))
else:
print("Element Not found")

OUTPUT:
The given array is [1, 2, 3, 4, 5, 6, 7]
Element to be found is 4
The Index of the element is 3

RESULT:
Thus the program of Binary search using Python is executed and the output is obtained
successfully.
EX. NO: 8
IMPLEMENTATION OF HASH TABLES
DATE:

AIM:
To write a python code for implementing hash table using separate chaining
ALGORITHM:
1. Start
2. Create Table size
3. Create hash function
4. To insert a node into the hash table, we need to find the hash index for the given key.
And it could be calculated using the hash function.
5. Display hash entry.
6. Stop
PROGRAM:
# Function to display hashtable
def display_hash(hashTable):
for i in range(len(hashTable)):
print(i, end = " ")
for j in hashTable[i]:
print("-->", end = " ")
print(j, end = " ")
print()
# Creating Hashtable as a nested list.
HashTable = [[] for _ in range(10)]
# Hashing Function to return key for every value.
def Hashing(keyvalue):
return keyvalue % len(HashTable)
# Insert Function to add values to the hash table
def insert(Hashtable, keyvalue,value):
hash_key = Hashing(keyvalue)
Hashtable[hash_key].append(value)
# Driver Code
insert(HashTable, 10, 'Allahabad')
insert(HashTable, 25,'Mumbai')
insert(HashTable, 20,'Mathura')
insert(HashTable, 9, 'Delhi')
insert(HashTable, 21, 'Punjab')
insert(HashTable, 21, 'Noida')
display_hash (HashTable)

OUTPUT:

RESULT:
Thus the program of Hash tables is executed and the output is obtained successfully.
EX. NO: 9 IMPLEMENTATION OF TREE REPRESENTATION
AND TRAVERSAL ALGORITHMS
DATE:

AIM:
To write a python program to implement the tree representation and its traversals
ALGORITHM:
1. Start
2. Create a Binary Tree for N elements
3. Insert an element in binary tree
4. Traverse the tree in inorder
5. Traverse the tree in preorder
6. Traverse the tree in postorder
7. Stop
PROGRAM:
class Node:
def init (self,
data): self.left =
None self.right =
None self.data =
data
# Creating tree and 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 theTree
def PrintTree(self):
ifself.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
# 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
# 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("Tree afterInordertraversal. .... ")
print(root.inorderTraversal(root))
print("Tree afterPreordertraversal. .... ")
print(root.PreorderTraversal(root))
print("Tree afterPostordertraversal. .... ")
print(root.PostorderTraversal(root))

OUTPUT:
Tree after Inorder traversal....
[10, 14, 19, 27, 31, 35, 42]
Tree after Preorder traversal....
[27, 14, 10, 19, 35, 31, 42]
Tree after Postorder traversal....
[10, 19, 14, 31, 42, 35, 27]

RESULT:
Thus the program of Tree representation and Traversal algorithms is executed and the output
is obtained successfully.
EX. NO: 10
IMPLEMENTATION OF BINARY SEARCH TREE
DATE:

AIM:
To write a python program for implementing Binary Search Tree (BST)
ALGORITHM:
1. Start the process.
2. Initialize and declare variables.
3. Construct the Tree
4. Data values are given which we call a key and a binary search tree
5. To search for the key in the given binary search tree, start with the root node and
Compare the key with the data value of the root node. If they 65 match, return the root
pointer.
6. If the key is less than the data value of the root node, repeat the process by using the
left subtree.
7. Otherwise, repeat the same process with the right subtree until either a match is found
or the subtree under consideration becomes an empty tree.
8. Check the specified node is present are not
9. Delete the specified branch from the tree
10. Terminate
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)
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:
returnself
if val <self.val:
ifself.left:
self.left = self.left.delete(val)
returnself
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:
returnFalse
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)
print("preorder:")
print(bst.preorder([]))
print("postorder:")
print(bst.postorder([]))
print("inorder:")
print(bst.inorder([]))
#deleting a branch
nums = [2, 6,20]
print("deleting " + str(nums))
for num innums:
bst.delete(num)
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, 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
2 exists:
False
12 exists:
True
18 exists:
True

RESULT:
Thus the program of Binary Search Tree is executed and the output is obtained successfully.
EX. NO: 11
IMPLEMENTATION OF HEAPS
DATE:

AIM:
To implement heaps using python
ALGORITHM:
1. Initialize an input array
2. Create a complete binary tree from the array
3. Start from the first index of non-leaf node whose index is given by n/2-1
4. Set current element I as largest
5. The index of the left child is given by 2i+1 and the right child is given by2i+2
• If leftChild is greater than current Element (i.e. element at I th index), set
left Child Index as largest.
• If rightChild is greater than element in largest, set rightChild Index as largest.
6. Swap largest with current Element
7. Repeat steps 3-7 until the subtrees are also heapified.
PROGRAM:
def heapify(arr, n, i):
largest = i
l=2*i+1
r = 2 * i +2
if l < n and arr[i] < arr[l]:
largest =l
if r < n and arr[largest] <arr[r]:
largest =r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr, n, largest)
def insert(array, newNum):
size = len(array)
if size == 0:
array.append(newNum)
else:
array.append(newNum);
for i in range((size//2)-1, -1, -1):
heapify(array, size, i)
def deleteNode(array, num):
size = len(array)
i=0
for i in range(0, size):
if num == array[i]:
break
array[i], array[size-1] = array[size-1], array[i]
array.remove(num)
for i in range((len(array)//2)-1, -1, -1):
heapify(array, len(array), i)
arr = []
insert(arr,3)
insert(arr,4)
insert(arr,9)
insert(arr,5)
insert(arr,2)
print ("Max-Heap array: " + str(arr))
deleteNode(arr, 4)
print("After deleting an element: " + str(arr))

OUTPUT:

Max-Heap array: [9, 5, 4, 3, 2]

After deleting an element: [9, 5, 2, 3]

RESULT:
Thus the program of Heaps is executed and the output is obtained successfully.
EX. NO: 12
GRAPH REPRESENTATION AND TRAVERSAL
DATE: ALGORITHMS

AIM:
To implement graph representation and traversal algorithms using python
ALGORITHM:
Depth First Search Algorithm
1. Define a stack of size total number of vertices in the graph
2. Select any vertex as the starting point for traversal. Visit that vertex and push it on to
the stack
3. Visit any one of the adjacent vertices of the vertex, that is at top of the stack and is not
visited, and push it on to the stack
4. Repeat step 3 until there are no new vertices to visit from each vertex on top of the
stack
5. When there is no new vertex to visit, use backtracking and pop one vertex from the
stack
6. Repeat steps 3,4, and 5 until stack becomes Empty
7. When stack becomes Empty, produce the final tree by removing unused edges from
the graph.
Breadth First Search Algorithm
1. Define a Queue of size total number of vertices in the graph
2. Select any vertex as the starting point for traversal. Visit that vertex and insert it into
the Queue
3. Visit all the adjacent vertices of the vertex, that is in front of the Queue and is not
visited, and insert them into the Queue
4. When there is no new vertex to visit from the vertex in front of the Queue, delete that
vertex from the Queue.
5. Repeat steps 3 and 4 until the queue becomes empty
6. When the queue becomes Empty, produce the final tree by removing the unused edges
from the graph
PROGRAM
Depth first traversal
def dfs_iterative(graph, start_vertex):
visited = set()
traversal = []
stack = [start_vertex]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
traversal.append(vertex)
# add vertex in the same order as visited
stack.extend(reversed(graph[vertex]))
return traversal
test_graph = {
'A': ['B', 'S'],
'B':['A'],
'C': ['D', 'E', 'F', 'S'],
'D':['C'],
'E': ['C','H'],
'F': ['C','G'],
'G': ['F','S'],
'H': ['E', 'G'],
'S': ['A', 'C', 'G']
}
print("Depth First Traversal")
print(dfs_iterative(test_graph, 'A'))
OUTPUT

Depth First Traversal

['A', 'B', 'S', 'C', 'D', 'E', 'H', 'G', 'F']

Breadth first traversal

def bfs(graph, start):


path = []
queue = [start]
while queue:
vertex = queue.pop(0)
if vertex not in path:
path.append(vertex)
queue.extend(graph[vertex])
return path
test_graph ={
'A': ['B','S'],
'B':['A'],
'C': ['D', 'E', 'F', 'S'],
'D':['C'],
'E': ['C','H'],
'F': ['C','G'],
'G': ['F','S'],
'H': ['E', 'G'],
'S': ['A', 'C', 'G']
}
print("Breadth First Traversal")
print(bfs(test_graph, 'A'))
OUTPUT

Breadth First Traversal

['A', 'B', 'S', 'C', 'G', 'D', 'E', 'F', 'H']

RESULT:
Thus the program of Graph representation and traversal algorithms is executed and the output
is obtained successfully.
EX. NO: 13
IMPLEMENTATION OF SINGLE SOURCE SHORTEST
DATE: PATH ALGORITHM

AIM:
To implement single source shortest path algorithm in python
ALGORITHM:
1. Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest
path tree, i.e., whose minimum distance from source is calculated and finalized.
Initially, this set is empty.
2. Assign a distance value to all vertices in the input graph. Initialize all distance values
as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first.
3. While sptSet doesn’t include all vertices:
• Pick a vertex u which is not there in sptSet and has minimum distance value.
• Include u to sptSet.
• Update distance value of all adjacent vertices of u. To update the distance
values, iterate through all adjacent vertices. For every adjacent vertex v, if
the sum of a distance value of u (from source) and weight of edge u-v, is less
than the distance value of v, then update the distance value of v.

PROGRAM:
Class Graph():
def init (self,
vertices): self.V =
vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
def printSolution(self,dist):
print("Vertex \t Distance from Source")
for node inrange(self.V):
print(node, "\t\t", dist[node])
# A utility function to find the vertex with minimum distance value, from the set of vertices
#not yet included in shortest path tree
def minDistance(self, dist, sptSet):
# Initialize minimum distance for next node
min = 1e7
# Search not nearest vertex not in the shortest path tree
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index
# Function that implements Dijkstra's single source shortest path algorithm for a graph # #
#represented using adjacency matrix representation
def dijkstra(self, src):
dist = [1e7] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
# Pick the minimum distance vertex from the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minDistance(dist, sptSet)
# Put the minimum distance vertex in the shortest path tree
sptSet[u] = True
# Update dist value of the adjacent vertices of the picked vertex only if the current
# distance is greater than new distance and the vertex in not in the shortest path tree
for v in range(self.V):
if (self.graph[u][v] >0 and
sptSet[v] == False and
dist[v] > dist[u] + self.graph[u][v]):
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)
# Driver program
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
g.d ijkstra(0)

OUTPUT:

RESULT:
Thus the program of single source shortest path algorithm is executed and the output is
obtained successfully.
EX. NO: 14
IMPLEMENTATION OF MINIMUM SPANNING TREE
DATE: ALGORITHMS

AIM:
To write a python code for implementing Minimum spanning tree algorithm
ALGORITHM:
1. Start with a weighted graph
2. Choose averted
3. Choose the shortest edge from this vertex and add it
4. Choose the nearest vertex not yet in the solution
5. Choose the nearest edge not yet in the solution, if there are multiple choices, choose
one at random
6. Repeat until you have a spanning tree
PROGRAM:
INF = 9999999
# number of vertices in graph
V=5
# create a 2d array of size 5x5 for adjacency matrix to represent graph
G = [[0, 9, 75, 0,0],
[9, 0, 95, 19,42],
[75, 95, 0, 51, 66],
[0, 19, 51, 0,31],
[0, 42, 66, 31,0]]
# create a array to track selected vertex selected will become true otherwise false
selected = [0, 0, 0, 0, 0]
# set number of edge to 0
no_edge =0
# the number of egde in minimum spanning tree will be always less than(V - 1), where V is
#number of vertices in graph. choose 0th vertex and make it true
selected[0] = True
# print for edge and weight
print("Edge : Weight\n")
while (no_edge < V - 1):
# For every vertex in the set S, find the all adjacent vertices, calculate the distance from the
#vertex selected at step 1. if the vertex is already in the set S, discard it otherwise
# choose another vertex nearest to selected vertex at step 1.
minimum =INF
x =0
y =0
for i in range(V):
if selected[i]:
for j in range(V):
if ((not selected[j]) and G[i][j]):
# not in selected and there is an edge
if minimum > G[i][j]:
minimum = G[i][j]
x =i
y =j
print(str(x) + "-" + str(y) + ":" + str(G[x][y]))
selected[y] = True
no_edge += 1

OUTPUT:

RESULT:
Thus the program of Minimum spanning tree algorithms is executed and the output is
obtained successfully.

You might also like