Dsa Lab 2025
Dsa Lab 2025
Department
of
Information technology
Practical Record Note
Name : ……………………………………………….............
Register No : ……………………………………….........................
BONAFIDE CERTIFICATE
6B APPLICATION OF STACK
6C APPLICATION OF QUEUE
7A LINEAR SEARCH
7B BINARY SEARCH
7C SELECTION SORT
7D INSERTION SORT
8 IMPLEMENTATION OF HASH
TABLES
9A TREE REPRESENTION
10 IMPLEMENTATION OF BINARY
SEARCH TREE
11 IMPLEMENTATION OF HEAPS
12A GRAPH REPRESENTION
12 B GRAPH TRAVERSAL
ALGORITHM
13 IMPLEMENTATION OF SINGLE
SOURCE SHORTEST PATH
ALGORITHM
14 IMPLEMENTATION OF
MINIMUM SPANNING TREES
ALGORITHM
Ex.No:1 IMPLEMENT SIMPLE ADTS AS PYTHON CLASSES
DATE :
AIM:
ALGORITHM:
2.Write function for all the basic operations of stack,Queue,List - PUSH(), POP() and
DISPLAY(),append(),Extend().
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack:')
print(stack)
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack)
# Queue
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print('\nInitial queue:')
print(queue)
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
# List
List = [1, 2, 3, 4]
print('\nInitial List:')
print(List)
Stack:
Initial stack
[]
Queue:
[]
List:
Initial List:
[1, 2, 3, 4]
DATE :
AIM:
ALGORITHM:
Step 1:Input the 'n' value until which the Fibonacci series has to be generated.
Step 7:sum = a + b
Step 10:Else
No = 10
num1, num2 = 0, 1
count = 0
if No<= 0:
print("Invalid Number")
elif No == 1:
print(num1)
else:
print("Fibonacci sequence:")
print(num1)
num1 = num2
num2 = nth
count += 1
OUTPUT:
Fibonacci sequence:
13
21
34
RESULT:
Thus the Implementation of recursive algorithms in Python using Fibonacci series was executed
successful
EX.NO:3 LIST ADT USING PYTHON ARRAYS
DATE :
AIM:
ALGORITHM:
class Node:
self.data = data
self.next = None
def add(data):
nn = Node(data)
return nn
i=0
while i< n:
i += 1
print() # To ensure the next line starts after the array is printed
def find_length(head):
cur = head
count = 0
count += 1
cur = cur.next
return count
def convert_arr(head):
length = find_length(head)
arr = []
current = head
arr.append(current.data)
current = current.next
return arr
# Example usage:
head = Node(6)
head.next = add(4)
head.next.next = add(3)
head.next.next.next = add(4)
array = convert_arr(head)
print_array(array, len(array))
Output:
[6,4,3,4]
[6 4 3 4)
RESULT:
DATE :
AIM:
ALGORITHM:
Step 2:Write function for all the basic operations of list - create(), insert(), deletion(),
display().
Step 3:Using append() to extend the elements, removal() to delete the elements
# Initial List
List = [1, 2, 3, 4]
print("Initial List:")
print(List)
# Extend Operation
print(List)
# Blank List
List = []
print("\nBlank List:")
print(List)
# List of numbers
print("\nList of numbers:")
print(List)
# List Items
print("\nList Items:")
print(List[0])
print(List[2])
List = [1, 2, 3, 4]
print("\nInitial List:")
print(List)
List.insert(3, 12)
List.insert(0, 'Geeks')
print(List)
# Initial List
print("\nInitial List:")
print(List)
# Removal of elements
List.remove(5)
List.remove(6)
print(List)
List.remove(i)
print(List)
# Multi-Dimensional List
print("\nMulti-Dimensional List:")
print(List)
OUTPUT:
[]
[1, 2, 4]
[1, 2, 4, 1, 2, 3]
>>>
=====================
Initial List:
[1, 2, 3, 4]
['Geeks', 1, 2, 3, 12, 4]
>>>
=====================
Intial List:
Thus the list was created, inserted, removed and extend the element was executed successfully.
EX.NO:5 IMPLEMENTATION OF STACK AND QUEUE ADTS
DATE :
AIM:
ALGORITHM:
Step 2:Write function for all the basic operations of stack - append(),POP()
# Stack
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack:')
print(stack)
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack)
# Queue
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print('\nInitial queue:')
print(queue)
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0)
('\nQueue after removing elements:')
print(queue)
Output:
Initial stack
[]
Result:
DATE :
AIM:
ALGORITHM:
declared.
elements.
size = max(m, n)
sum[i] = A[i]
for i in range(n):
sum[i] += B[i]
return sum
for i in range(n):
print(poly[i], end="")
if i != 0:
print("x^", i, end="")
if i != n - 1:
print() # To ensure the next line starts after the polynomial is printed
if __name__ == '__main__':
A = [5, 0, 10, 6]
B = [1, 2, 4]
m = len(A)
n = len(B)
printPoly(A, m)
print("Second polynomial is")
printPoly(B, n)
sum = add(A, B, m, n)
size = max(m, n)
printPoly(sum, size)
OUTPUT:
First polynomial is
Second polynomial is
1 + 2x^1 + 4x^2
Sum polynomial is
6 + 2x^1 + 14x^2 + 6x
RESULT :
DATE
ALGORITHM:
Step 2:Write function for all the basic operations of stack - append(), POP()
Stack implementation
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack)
# Queue implementation
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
DATE
ALGORITHM:
Step 2: check if empty or not ,the stack will insert the elements.
Step 4: Check the operator based on the precedence the expression will be evaluated
class Conversion:
self.top = -1
self.capacity = capacity
self.array = []
self.output = []
def isEmpty(self):
return self.top == -1
def peek(self):
return self.array[-1]
def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$"
self.top += 1
self.array.append(op)
return ch.isalpha()
try:
a = self.precedence[i]
b = self.precedence[self.peek()]
except KeyError:
return False
for i in exp:
if self.isOperand(i):
self.output.append(i)
elif i == '(':
self.push(i)
elif i == ')':
a = self.pop()
self.output.append(a)
return -1
else:
self.pop()
else:
self.output.append(self.pop())
self.push(i)
while not self.isEmpty():
self.output.append(self.pop())
print("".join(self.output))
exp = "a+b*(c^d-e)^(f+g*h)-i"
obj = Conversion(len(exp))
obj.infixToPo
OUTPUT: abcd^e-fgh*+^*+i
DATE
ALGORITHM:
1. Input the number of processes required to be scheduled using FCFS, burst time for each process and its
arrival time.
2. Calculate the Finish Time, Turn Around Time and Waiting Time for each process which in turn help to
calculate Average Waiting Time and Average Turn Around Time required by CPU to schedule given set
of process using FCFS.
3. Process with less arrival time comes first and gets scheduled first by the CPU
. 4. Calculate the Average Waiting Time and Average Turn Around Time
wt[0] = 0
for i in range(n):
wt = [0] * n
tat = [0] * n
total_wt = 0
total_tat = 0
for i in range(n):
total_wt += wt[i]
total_tat += tat[i]
if _name_ == "_main_"
processes = [1, 2, 3]
n = len(processes)
burst_time = [10, 5, 8]
findavgTime(processes, n, burst_time
Output:
1 10 0 10
2 5 10 15
3 8 15 23
DATE
ALGORITHM:
Step 1: Start
x):
found = True
if (found == False):
Thus the python program for the implementation of linear search was executed and the output was
obtained.
Ex.No:7B BINARY SEARCH
DATE
STEP 6: Repeat step 7 to 12 until first <=last and not to found occur false.
first = 0
last = len(item_list) - 1
found = False
if item_list[mid] == item:
found = True
else:
last = mid - 1
else:
first = mid + 1
return foundprint
Thus the python program for the implementation of binary search was executed and output was obtained.
EX.NO:7C SELECTION SORT
DATE:
ALGORITHM:
STEP 1: Start
def selectionSort(alist):
positionOfMax = 0
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp
alist = [45, 62, 13, 71, 77, 31, 49, 53, 20]
selectionSort(alist)
print(alist)
OUTPUT
13,20,31,45,49,53,62,71,77
RESULT :
Thus the python program for the implementation of selection sort was executed and the output was
obtained.
EX.NO:7D INSERTION SORT
DATE:
STEP 6: Repeat the step 7 to step 8 until position >0 and alist[position1]>current value occur false.
def insertionSort(alist):
currentvalue = alist[index]
position = index
alist[position] = alist[position - 1]
position = position - 1
alist[position] = currentvalue
alist = [15, 22, 39, 41, 67, 73, 85, 86, 90]
insertionSort(alist)
print(alist)
OUTPUT: 15,22,39,41,67,73,58,56,90
RESULT: Thus the python program for the implementation of insertion sort was executed and output was
obtained.
EX.NO:8 IMPLEMENTATION OF HASH TABLES
DATE:
ALGORITHM:
1.Create a structure, data (hash table item) with key and value as data.
def checkPrime(n):
if n <= 1:
return False
for i in range(2, n // 2 + 1)
if n % i == 0:
return False
return True
def getPrime(n):
if n % 2 == 0:
n += 1
n += 2
return n
def hashFunction(key):
capacity = getPrime(10)
index = hashFunction(key)
def removeData(key):
index = hashFunction(key)
hashTable[index] = []
insertData(123, "apple")
insertData(432, "mango")
insertData(213, "banana")
insertData(654, "guava")
print(hashTable)
removeData(123)
print(hashTable)
OUTPUT: [[], [], [123, 'apple'], [432, 'mango'], [213, 'banana'], [654, 'guava'], [], [], [], []] [[], [], 0, [432,
'mango'], [213, 'banana'], [654, 'guava'], [], [], [], []]
RESULT: Thus the Implementation of hashing was executed successful
Ex.No:9a Tree representation
DATE
ALGORITHM:
2.Intially all the left and right vertex are none , then declare the values using insert()
class Node:
self.left = None
self.right = None
self.data = data
if self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def PrintTree(self):
if self.left:
self.left.PrintTree()
if self.right
self.right.PrintTree()
# Example usage
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
root.PrintTree()
Output: 3 6 12 14
Result: Thus the binary tree was successfully created
Ex.No:9b Tree Traversal Algorithms
DATE:
Algorithm:
Postorder(tree)
class Node:
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left)
printInorder(root.right)
def printPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
def printPreorder(root):
if root:
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)
printPreorder(root)
printInorder(root)
printPostorder(root)
Ex.No: 10 Implementation of Binary Search Trees
DATE:
Aim:
Algorithm:
Step 2 - Compare the search element with the value of root node in the tree.
Step 3 - If both are matched, then display "Given node is found!!!" and terminate the function
Step 4 - If both are not matched, then check whether search element is smaller or larger than that node
value
Step 5 - If search element is smaller, then continue the search process in left subtree.
Step 6- If search element is larger, then continue the search process in right subtree.
Step 7 - Repeat the same until we find the exact element or until the search element is compared with leaf
node
Step 8 - If we reach to the node having the value equal to the search value then display "Elementis found"
and terminate the function.
PROGRAM :
class Node:
self.left = None
self.right = None
self.data = data
if self.data:
if data <self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
if lkpval<self.data:
if self.left is None:
return self.left.findval(lkpval)
eliflkpval>self.data
if self.right is None:
return self.right.findval(lkpval)
else:
def PrintTree(self):
if self.left:
self.left.PrintTree()
if self.right:
self.right.PrintTree()
# Example usage:
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
print(root.findval(7))
root.PrintTree()
Output:
7 Not Found
14 is found
RESULT :
Thus the Implementation of Binary Search Trees using python was executed successful
Ex.NO:11 Implementation of Heaps
DATE :
Aim:
Algorithm:
import heapq
H = [21,1,45,78,3,5]
heapq.heapify(H)
print(H)
heapq.heappush(H,8)
print(H)
heapq.heappop(H)
print(H)
Output:
1, 3, 5, 78, 21, 45
DATE :
Aim:
ALGORITHM :
Set adj_matrix[u][v] = 1.
class Graph:
if gdict is None:
gdict = {}
self.gdict = gdict
def getVertices(self):
return list(self.gdict.keys())
def edges(self):
return self.findedges()
def findedges(self):
edgename = []
edgename.append({vrtx, nxtvrtx})
return edgename
# Example usage
graph_elements = {
"d": ["e"],
"e": ["d"]
}
g = Graph(graph_elements)
print("Vertices of graph:")
print(g.getVertices())
print("Edges of graph:")
print(g.edges())
Output:
DISPLAYING VERTICES
DISPLAYING EDGES
[{'a', 'b'}, {'a', 'c'}, {'d', 'b'}, {'c', 'd'}, {'d', 'e}
RESULT :
DATE:
Aim:
Algorithm:
DFS:
Step 2 - Select any vertex as starting point for traversal. Visit that vertex and push it on to the stack.
Step 3 - Visit any one of the non-visited adjacent vertices of a vertex which is at the top of stack and push
it on the stack.
Step 4 - Repeat step 3 until there is no new vertex to be visited from the vertex which is at thetop of the
stack.
Step 5 - When there is no new vertex to visit then use back tracking and pop one vertex from thestack.
Step 7 - When stack becomes Empty, then produce final spanning tree by removing unused edgefrom the
graph
BFS:
Step 2 - Select any vertex as starting point for traversal. Visit that vertex and insert it into theQueue.
Step 3 - Visit all the non-visited adjacent vertices of the vertex which is at front of the Queue andinsert
them into the Queue.
Step 4 - When there is no new vertex to be visited from the vertex which is at front of the Queuethen
delete that vertex.
Step 6 - When queue becomes empty, then produce final spanning tree by removing unused edgesfrom
the graph
BFS PROGRAM :
import collections
visited.add(root)
while queue:
vertex = queue.popleft()
visited.add(neighbour)
queue.append(neighbour)
if __name__ == '__main__':
bfs(graph, 0)
Output:
012
DFS PROGRAM :
import sys
def ret_graph():
return {
start = 'A'
dest = 'J'
visited = []
stack = []
graph = ret_graph()
path = []
stack.append(start)
visited.append(start)
while stack:
curr = stack.pop()
path.append(curr)
visited.append(neigh)
stack.append(neigh)
if neigh == dest:
print("FOUND:", neigh)
print(path)
sys.exit(0)
print("Not found")
print(path)
Output:
FOUND: J
DATE:
Aim:
To Implement single source shortest path algorithm using Bellman Ford Algorithm
Algorithm:
1) This step initializes distances from source to all vertices as infinite and distance to source itself as 0.
Create an array dist[] of size |V| with all values as infinite except dist[src] where src is source vertex.
2) This step calculates shortest distances. Do following |V|-1 times where |V| is the number ofvertices in
given graph.
3)Do following for each edge u-vIf dist[v] >dist[u] + weight of edge uv, then update dist[v]dist[v] =
dist[u] + weight of edge uv
4) This step reports if there is a negative weight cycle in graph. Do following for each edge u-vIf
dist[v] >dist[u] + weight of edge uv, then “Graph contains negative weight cycle”The idea of step 3 is,
step 2 guarantees shortest distances if graph doesn’t contain negative weight cycle. If we iterate through
all edges one more time and get a shorter path for any vertex,then there is a negative weight cycle
PROGRAM :
dis = [maxsize] * V
dis[src] = 0
for j in range(E):
for i in range(E):
x = graph[i][0]
y = graph[i][1]
weight = graph[i][2]
return
for i in range(V):
if __name__ == "__main__":
graph = [
BellmanFord(graph, V, E, 0)
Output:
00
1 -1
22
3 -2
RESULT :
Thus the Implementation of single source shortest path algorithm was successfully execute
Ex.No:14 Implementation of minimum spanning tree algorithms
DATE:
Aim:
Algorithm:
3. Start with the smallest weighted and beginning growing the minimum weighted spanning tree from this
edge.
4. Add the next available edge that does not form a cycle to the construction of the minimum weighted
spanning tree. If the addition of the next least weighted edge forms a cycle, do not use it.
class Graph:
self.V = vertices
self.graph = []
self.graph.append([u, v, w])
if parent[i] == i:
return i
xroot = self.find(parent, x)
yroot = self.find(parent, y)
parent[xroot] = yroot
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def kruskal_algo(self):
result = []
i, e = 0, 0
parent = []
rank = []
parent.append(node)
rank.append(0)
while e <self.V - 1:
u, v, w = self.graph[i]
i=i+1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e=e+1
result.append([u, v, w])
self.apply_union(parent, rank, x, y)
# Example usage
g = Graph(6)
g.add_edge(0, 1, 4)
g.add_edge(0, 2, 4)
g.add_edge(1, 2, 2)
g.add_edge(1, 0, 4)
g.add_edge(2, 0, 4)
g.add_edge(2, 1, 2)
g.add_edge(2, 3, 3)
g.add_edge(2, 5, 2)
g.add_edge(2, 4, 4)
g.add_edge(3, 2, 3)
g.add_edge(3, 4, 3)
g.add_edge(4, 2, 4)
g.add_edge(4, 3, 3)
g.add_edge(5, 2, 2)
g.add_edge(5, 4, 3)
g.kruskal_algo()
Output:
1 - 2: 2
2 - 5: 2
2 - 3: 3
3 - 4: 3
RESULT :