I B.Sc.,Python Lab (2023-2024)
I B.Sc.,Python Lab (2023-2024)
I B.Sc.,Python Lab (2023-2024)
(Accredited with “C” Grade by NAAC & Affiliated to the Periyar University)
Vadachennimalai (Po), Attur (T.K),
Salem (D.T) - 636121
Ph.No.04282-235001, www.aagacattur.org.in
NAME
CLASS
SUBJECT
Certified that this a bonafide record of the work done in Arignar Anna Govt. Arts college, in the
Computer Laboratory during the academic year 2023-2024.
Submitted for the University Practical Examination held on
1.
2.
INDEX
PAGE
EX.
DATE CONTENT NO SIGN
NO
2
STACK AND QUEUE ADT
3
IMPLEMENT THE LIST ADT
4
IMPLEMENT PRIORITY QUEUE ADT
8
META AND BINARY SEARCH
AIM:
To write a Python program that appends, deletes and displays elements of a list using classes.
ALGORITHM:
Step 1: Create a class and using a constructor initialize values of that class.
Step 2: Create methods for adding, removing and displaying elements of the list and return the respective
values.
Step 4: Using the object, call the respective function depending on the choice taken from the user.
Step 6: Exit
PROGRAM:
class SimpleListADT:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def add(self, item):
self.items.append(item)
def remove(self, item):
if item in self.items:
self.items.remove(item)
else:
print(f"{item} not found in the list.")
# Example usage:
my_list = SimpleListADT()
print("Is the list empty?", my_list.is_empty())
print("Size of the list:", my_list.size())
my_list.add(1)
my_list.add(2)
my_list.add(3)
print("Is the list empty?", my_list.is_empty())
print("Size of the list:", my_list.size())
print("List items:", my_list.items)
my_list.remove(2)
print("Size of the list after removing 2:", my_list.size())
print("List items after removal:", my_list.items)
OUTPUT:
Is the list empty? True
Size of the list: 0
Is the list empty? False
Size of the list: 3
List items: [1, 2, 3]
Size of the list after removing 2: 2
List items after removal: [1, 3]
RESULT:
Thus, the Python program that appends, deletes and displays elements of a list using classes has
been implemented successfully.
/* PROGRAMS TO IMPLEMENT THE FOLLOWING USING A SINGLY
LINKED LIST */
A. IMPLEMENTATION OF STACK
AIM:
To write a python program creates a stack and allows the user to perform push
and pop operations on it.
ALGORITHM:
Step 1: Create a class Node with instance variables data and next.
Step 3: The variable head points to the first element in the linked list.
Step 4: Define methods push and pop inside the class Stack.
Step 5: The method push adds a node at the front of the linked list.
Step 6: The method pop returns the data of the node at the front of the linked list and
removes the node. It returns None if there are no nodes.
Step 7: Create an instance of Stack and present a menu to the user to perform operations
on the stack.
PROGRAM:
class Stack_struct:
def __init__(self):
self.items = []
def check_empty(self):
return self.items == []
def add_elements(self, my_data):
self.items.append(my_data)
def delete_elements(self):
return self.items.pop()
my_instance = Stack_struct()
while True:
print('Push <value>')
print('Pop')
print('Quit')
my_input = input('What operation would you like to perform ? ').split()
my_op = my_input[0].strip().lower()
if my_op == 'push':
my_instance.add_elements(int(my_input[1]))
elif my_op == 'pop':
if my_instance.check_empty():
print('The stack is empty')
else:
print('The deleted value is : ', my_instance.delete_elements())
elif my_op == 'Quit':
break
OUTPUT
Push <value>
Pop
Quit
What operation would you like to perform? Push 6
Push <value>
Pop
Quit
What operation would you like to perform? Push 8
Push <value>
Pop
Quit
What operation would you like to perform? Push 34
Push <value>
Pop
Quit
What operation would you like to perform? Pop
The deleted value is : 6
Push <value>
Pop
Quit
RESULT:
Thus the python program to creates a stack and allows the user to perform push and pop
operations on it has been executes successfully
B. IMPLEMENTATION OF QUEUE
AIM:
To write a python program creates a queue and allows the user to perform enqueue and
dequeueoperations on it.
ALGORITHM:
Step 1: Create a class Node with instance variables data and next.
Step 2: Create a class Queue with instance variables head and last.
Step 3: The variable head points to the first element in the linked list while last points to
the last element.
Step 4: Define methods enqueue and dequeue inside the class Queue.
Step 5: The method enqueue adds a node at the end of the linked list.
Step 6: The method dequeue returns the data of the node at the front of the linked list and
removes the node. It returns None if there are no nodes.
Step 7: Create an instance of Queue and present a menu to the user to perform operations
on thequeue.
PROGRAM:
class Queue_struct:
def __init__(self):
self.items = []
def check_empty(self):
return self.items == []
def enqueue_elem(self, data):
self.items.append(data)
def dequeue_elem(self):
return self.items.pop(0)
my_instance = Queue_struct()
while True:
print('Enqueue <value>')
print('Dequeue')
print('Quit')
my_input = input('What operation would you perform ? ').split()
operation = my_input[0].strip().lower()
if operation == 'Enqueue':
my_instance.enqueue_elem(int(my_input[1]))
elif operation == 'Dequeue':
if my_instance.check_empty():
print('The queue is empty...')
else:
print('The deleted value is : ', my_instance.dequeue_elem())
elif operation == 'Quit':
break
OUTPUT
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Enqueue 45
Enqueue <value>
Dequeue
Quit
What operation would you perform? Enqueue 56
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Enqueue 89
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Dequeue
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Dequeue
Enqueue <value>
Dequeue
Quit
What operation would you perform ? Quit
RESULT:
Thus, the python program to creates a queue and allows the user to perform enqueue and
dequeue operations on it has been executes successfully.
/*PROGRAM TO IMPLEMENT THE LIST ADT USING PYTHON ARRAYS*/
AIM:
To write a Python program to implement list using Array and linked list.
ALGORITHM:
Step 1: Start.
Step 2: Declare the necessary functions for implementation. Get the input from the user
and store it an array and linked list.
Step 3: In Insertion, half of the elements to be shifted upwards and in deletion half of the
elements to be shifted downwards.
Step 5: Stop.
PROGRAM:
//Accessing Array Element
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
//Insertion Operation
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])
from array import *
array1 = array('i', [10,20,30,40,50])
array1.insert(1,60)
for x in array1:
print(x)
//Deletion Operation
from array import *
array1 = array('i', [10,20,30,40,50])
array1.remove(40)
for x in array1:
print(x)
// Search Operation
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1.index(40))
//Update Operation
from array import *
array1 = array('i', [10,20,30,40,50])
array1[2] = 80
for x in array1:
print(x)
OUTPUT
RESULT:
Thus, the Python program for creation and insertion to implement list using an array has
been executed successfully.
/* PROGRAM TO IMPLEMENT PRIORITY QUEUE ADT* /
AIM:
To write a Python program to implement priority Queue ADT.
ALGORITHM:
Step 1: Start the Program.
Step 2: The Node class will be the element inserted in the priority queue.
Step 3: To add a new data element (Node) in the priority queue.If the priority queue is
Step 4: When we remove a data from a priority queue(min), the data at the top, which
RESULT:
Thus, the python program to creates a queue and allows the user to perform Priority
Queue operations on it has been executes successfully.
/*PROGRAM TO PERFORM THE INSERT, DELETE AND SEARCH KEY
ELEMENT */
AIM:
To write a python program creates a binary search tree and presents a
menu to the user to perform insertion, deletion and inorder traversal
operations.
ALGORITHM:
Step 1:Start the Program
Step 2: Given a BST, the task is to insert a new node in this BST.
Step 3: Check the value to be inserted (say X) with the value of the current node
(say val)
Step 4: Once the leaf node is reached, insert X to its right or left based on the relation
between X and the leaf node’s value.
Step 5: Display the result using insert an Binary Search Tree.
Step 6: Stop the Program.
PROGRAM:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
else:
if root.val == key:
return root
elif root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return root
def inorder(root):
if root:
inorder(root.left)
print(root.val, end=" ")
inorder(root.right)
if __name__ == '__main__':
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)
inorder(r)
OUTPUT:
> 10
20 30 40 50 60 70 80 10
RESULT:
Thus, the python program to implement the concept of binary search tree. has been
implemented successfully.
/* B. DELETE AN ELEMENT FROM A BINARY SEARCH TREE */
AIM:
To write a python program creates a binary search tree and presents a
menu to the user to perform insertion, deletion and inorder traversal
operations.
ALGORITHM:
Step 1: Start the Program.
Step 2: The method replace_node_of_parent takes a node as argument and replaces the
current object in the BST with the node.
Step 3: The method find_min finds the the left-most node in the BST with the BSTNode
object as root.
Step 4: The method remove removes the current BSTNode object from the BST.
OUTPUT:
Inorder traversal after insertion: 2 4 5 6 8 9 10
2 is deleted: 4 5 6 8 9 10
4 is deleted: 5 6 8 9 10
6 is deleted: 5 8 9 10
RESULT:
Thus, the python program to implement the concept of binary search tree. has been
implemented successfully.
/* C. SEARCH FOR A KEY ELEMENT IN A BINARY SEARCH TREE */
AIM:
To write a python program creates a binary search tree and presents a menu to the user to
perform insertion, deletion and inorder traversal operations.
ALGORITHM:
Step 1: Start the Program.
Step 2: The method search takes a key as argument and returns the node with that key in
the BST withthe BSTNode object as root.
Step 3: Create a class BSTree with instance variable root.
Step 4: Define methods inorder, add, remove and search in BSTree.
Step 5: The method inorder calls the inorder method of the root node.\
Step 6: Display the result using Binary Search Tree.
Step 7: Stop the program.
PROGRAM:
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return node
def search(root, key):
if root is None or root.key == key:
return root
if root.key < key:
return search(root.right, key)
return search(root.left, key)
if __name__ == '__main__':
root = None
root = insert(root, 50)
insert(root, 30)
insert(root, 20)
insert(root, 40)
insert(root, 70)
insert(root, 60)
insert(root, 80)
key = 6
if search(root, key) is None:
print(key, "not found")
else:
print(key, "found")
key = 60
if search(root, key) is None:
print(key, "not found")
else:
print(key, "found")
OUTPUT
6 not found
60 found
RESULT:
Thus, the python program to implement the concept of binary search tree. has been
implemented successfully.
/* PROGRAM TO PERFORM THE INSERTION AND DELETION FROM AN
AVL-TREE */
AIM:
To write a python program creates a AVL tree and presents a menu to the user to
perform insertion, operations.
ALGORITHM:
Step 1: Start the Program.
Step 2 - Insert the new element into the tree using Binary Search Tree insertion logic.
Step 4 - If the Balance Factor of every node is 0 or 1 or -1 then go for next operation.
Step 5 - If the Balance Factor of any node is other than 0 or 1 or -1 then that tree is
said to be imbalanced. In this case, perform suitable Rotation to make it balanced and go
RESULT:
Thus, the python program to implement the concept of insertion an AVL tree. has been
implemented successfully.
/*B. DELETION FROM AN AVL-TREE */
AIM:
To write a python program creates a AVL tree and presents a menu to the user to
perform deletion, operations.
ALGORITHM:
Step 1: Start the Program.
Step 2 - Delete the element into the tree using Binary Search Tree deletion logic.
Step 3 - After deletion, check the Balance Factor of every node.
Step 4 - If the Balance Factor of every node is 0 or 1 or -1 then go for next operation.
Step 6: Display the result using AVL Tree.
Step 7: Stop the program.
PROGRAM
class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.height = 1
class AVLTree(object):
def insert(self, root, key):
if not root:
return Node(key)
elif key < root.data:
root.left = self.insert(root.left, key)
else:
root.right = self.insert(root.right, key)
root.h = 1 + max(self.getHeight(root.left),
self.getHeight(root.right))
b = self.getBalance(root)
if b > 1 and key < root.left.data:
return self.rightRotate(root)
if b < -1 and key > root.right.data:
return self.leftRotate(root)
if b > 1 and key > root.left.data:
root.left = self.lefttRotate(root.left)
return self.rightRotate(root)
if b < -1 and key < root.right.data:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
def delete(self, root, key):
if not root:
return root
elif key < root.data:
root.left = self.delete(root.left, key)
elif key > root.data:
root.right = self.delete(root.right, key)
else:
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
temp = self.getMindataueNode(root.right)
root.data = temp.data
root.right = self.delete(root.right, temp.data)
if root is None:
return root
root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right))
balance = self.getBalance(root)
if balance > 1 and self.getBalance(root.left) >= 0:
return self.rightRotate(root)
if balance < -1 and self.getBalance(root.right) <= 0:
return self.leftRotate(root)
if balance > 1 and self.getBalance(root.left) < 0:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)
if balance < -1 and self.getBalance(root.right) > 0:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
def leftRotate(self, z):
y = z.right
T2 = y.left
y.left = z
z.right = T2
z.height = 1 + max(self.getHeight(z.left),
self.getHeight(z.right))
y.height = 1 + max(self.getHeight(y.left),
self.getHeight(y.right))
return y
def rightRotate(self, z):
y = z.left
T3 = y.right
y.right = z
z.left = T3
z.height = 1 + max(self.getHeight(z.left),
self.getHeight(z.right))
y.height = 1 + max(self.getHeight(y.left),
self.getHeight(y.right))
return y
def getHeight(self, root):
if not root:
return 0
return root.height
def getBalance(self, root):
if not root:
return 0
return self.getHeight(root.left) - self.getHeight(root.right)
def Inorder(self, root):
if root.left:
self.Inorder(root.left)
print(root.data, end = " ")
if root.right:
self.Inorder(root.right)
Tree = AVLTree()
root = None
root = Tree.insert(root, 10)
root = Tree.insert(root, 13)
root = Tree.insert(root, 11)
root = Tree.insert(root, 14)
root = Tree.insert(root, 12)
root = Tree.insert(root, 15)
# Inorder Traversal
print("AVL Tree: ")
Tree.Inorder(root)
root = Tree.delete(root, 14)
print("\nAfter deletion: ")
Tree.Inorder(root)
OUTPUT:
AVL Tree:
10 11 12 13 14 15
After deletion:
10 11 12 13 15
RESULT:
Thus, the python program to implement the concept of insertion an AVL tree. has been
implemented successfully.
/*PROGRAMS FOR THE IMPLEMENTATION OF BFS AND DFS FOR A
GIVEN GRAPH*/
AIM:
To write a Python program to implementation of BFS and DFS for a given graph.
ALGORITHM:
Step 1: Start the program.
Step 2: The BFS and DFS algorithm will traverse all the nodes in the graph starting from
the root and keep them dropping after they are completed or visited:-
Step 3: BFS and DFS visits an adjacent unvisited node, marks it as done, and inserts it
into a queue.
Step 4: Remove the previous vertex from the queue if in case there is no adjacent vertex.
Step 5: BFS and DFS algorithm will iterate until all the vertices are traversed.
RESULT
Thus, the python program to implement the BFS and DFS for a given graph . has been
implemented successfully.
/*PROGRAMS FOR IMPLEMENTING THE META SEARCH AND BINARY
SEARCH*/
AIM:
To write a Python program to implementation of meta search and binary search
for a searching methods.
ALGORITHM:
Step 1: Start the Program.
Step 2: Compare the middle element of the search space with the key.
Step 4: If the key is not found at middle element, choose which half will be used as the
OUTPUT
1
//BINARY SEARCH
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l) // 2
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# If we reach here, then the element
# was not present
return -1
# Driver Code
if __name__ == '__main__':
arr = [2, 3, 4, 10, 40]
x = 10
# Function call
result = binarySearch(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", result)
else:
print("Element is not present in array")
OUTPUT
Element is present at index 3
RESULT
Thus, the python program to implement the Meta and binary search for a sorting methods
has been implemented successfully.
/*PROGRAMS FOR IMPLEMENTING BUBBLE, SELECTION AND
INSERTION SORTING METHODS*/
AIM:
To Perform the Bubble. Selection and Insertion Sorting in Python Programming.
ALGORITHM:
Step 1: Start
Step 3: Take first element find its appropriate position and insert them
Step 6: Stop
PROGRAM:
// BUBBLE SORTING
def bubblesort(list):
# Swap the elements to arrange in order
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx]>list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
list = [19,2,31,45,6,11,121,27]
bubblesort(list)
print(list)
OUTPUT
[2, 6, 11, 19, 27, 31, 45, 121]
//SELECTION SORTING
def selection_sort(input_list):
for idx in range(len(input_list)):
min_idx = idx
for j in range( idx +1, len(input_list)):
if input_list[min_idx] > input_list[j]:
min_idx = j
# Swap the minimum value with the compared value
input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx]
l = [19,2,31,45,30,11,121,27]
selection_sort(l)
print(l)
OUTPUT
[2, 11, 19, 27, 30, 31, 45, 121]
//INSERTION SORTING
def insertion_sort(InputList):
for i in range(1, len(InputList)):
j = i-1
nxt_element = InputList[i]
# Compare the current element with next one
while (InputList[j] > nxt_element) and (j >= 0):
InputList[j+1] = InputList[j]
j=j-1
InputList[j+1] = nxt_element
list = [19,2,31,45,30,11,121,27]
insertion_sort(list)
print(list)
OUTPUT
[19, 2, 31, 45, 30, 11, 27, 121]
RESULT:
Thus, the python program to perform Bubble, Insertion, and Selection Sort is created and
executed successfully.