DSD Lab Final
DSD Lab Final
Ex. No PROGRAMS
Aim:
To Implement simple ADTs as Python classes using Stack,Queue,List using python.
Algorithm:
Coding :
Stack:
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
print('\nElements poped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are poped:')
print(stack)
Queue:
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)
List:
List = [1,2,3,4]
print("Initial List: ")
print(List)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)
Output:
Stack:
Initial stack
['a', 'b', 'c']
Elements poped from stack:
c
b
a
Stack after elements are poped:
[]
Queue:
['a', 'b', 'c']
Elements dequeued from queue
a
b
c
Queue after removing elements
[]
List:
Initial List:
[1, 2, 3, 4]
List after performing Extend Operation:
[1, 2, 3, 4, 8, 'Geeks', 'Always']
Result:
Thus the Implementation of simple ADTs Python classes was executed successfully.
Ex.No:2 Implement recursive algorithms in Python
Aim:
To Implement a recursive algorithms in Python using Fibonacci Series
Algorithm:
1. Input the 'n' value until which the Fibonacci series has to be generated
2. Initialize sum = 0, a = 0, b = 1 and count = 1
3. while (count <= n)
4. print sum
5. Increment the count variable
6. swap a and b
7. sum = a + b
8. while (count > n)
9. End the algorithm
10. Else
11. Repeat from steps 4 to 7
Coding:
No = 10
num1, num2 = 0, 1
count = 0
if No <= 0:
print("Invalid Number")
elif No == 1:
print("Fibonacci sequence for limit of ",No,":")
print(num1)
else:
print("Fibonacci sequence:")
while count < No:
print(num1)
nth = num1 + num2
num1 = num2
num2 = nth
count += 1
Output:
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
Result:
Thus the Implementation of recursive algorithms in Python using Fibonacci series was
executed successfully.
Ex.No:3 Implement List ADT using Python arrays
Aim:
To Implement List ADT using Python arrays.
Algorithm
1. Using define function initialize the list.
2. While loop to declare the elements until the condition is satisfied.
3. Using convert arr function to convert the elements to an array
4.Stop the program
Coding:
class Node:
def __init__(self, data):
self.data = data
self.next = None
def add(data):
return Node(data)
def printarray(a, n):
i=0
while i < n:
print(a[i], end=" ")
i += 1
print()
def findlength(head):
cur = head
count = 0
while(cur!=None):
count=count+1
cur = cur.next
return count
def convertarr(head):
len = findlength(head)
arr = []
cur = head
while(cur!=None):
arr.append(cur.data)
cur = cur.next
printarray(arr, len)
head = add(6)
head.next = add(4)
head.next.next = add(3)
head.next.next.next = add(4)
convertarr(head)
Output:
[6,4,3,4]
Result:
Thus the implementation of List in arrays was executed successfully.
Ex.NO:4 Linked list implementations of List
Aim:
To Implement the Linked list implementations of List using python
Algorithm:
1. Create a list[ ] with MAX size as your wish.
2. Write function for all the basic operations of list - create(), insert(), deletion(), display().
3.Using append() to extend the elements, removal() to delete the elements
3. Close the program.
Coding:
# Initializing a list
List = [1, 2, 3, 4]
print("Initial List:")
print(List)
Aim:
To Implementation of Stack and Queue ADTs
Algorithm:
Queue:
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)
Output:
Initial stack
['a', 'b', 'c']
Elements poped from stack:
c
b
a
Stack after elements are poped:
[]
Result:
Thus the program for Implementation of Stack and Queue ADTs executed successfully
Ex.No:6a Application of List
Aim:
To implement list application using Polynomial Addition in python
Algorithm:
1. Using the define function initial elements will be declared.
2. For loop gives the output of sum of the elements
3. print [poly] statement have the sum of two polynomial elements.
4. Close the program
Coding:
return sum_poly
if i == 0:
print(poly[i], end="") # First term doesn't need 'x'
else:
print(f" + {poly[i]}x^{i}", end="") # Correct format for terms
sum_poly = add(A, B, m, n)
size = max(m, n)
Output:
First polynomial is
5 + 0x^1 + 10x^2 + 6x^3
Second polynomial is
1 + 2x^1 + 4x^2
Sum polynomial is
6 + 2x^1 + 14x^2 + 6x^3
Result:
Thus the program was executed successfully.
Ex.No:6b Application of Stack
Aim:
To implement the conversion of infix to postfix in stack
Algorithm:
1. Read the given expression
2. Check ifempty or not ,the stack will insert the elements. 3.
Using push(),pop() to insert the element or remove the element.
4. Check the operator based on the precedence the expression will be evaluated
5.Close the program
Coding:
class Conversion:
def __init__(self, capacity):
self.top = -1
self.capacity = capacity
self.array = []
self.output = []
self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
def isEmpty(self):
return self.top == -1
def peek(self):
return self.array[-1] if not self.isEmpty() else None
def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$" # Error indicator
def push(self, op):
self.top += 1
self.array.append(op)
def isOperand(self, ch):
return ch.isalpha() or ch.isdigit() # Allow numbers as well
def notGreater(self, i):
try:
a = self.precedence[i]
b = self.precedence.get(self.peek(), -1) # Avoid KeyError
return a <= b
except KeyError:
return False
def infixToPostfix(self, exp):
for i in exp:
if self.isOperand(i):
self.output.append(i)
elif i == '(':
self.push(i)
elif i == ')':
while (not self.isEmpty()) and self.peek() != '(':
self.output.append(self.pop())
if (not self.isEmpty() and self.peek() == '('):
self.pop() # Remove '(' from stack
else:
while (not self.isEmpty() and self.notGreater(i)):
self.output.append(self.pop())
self.push(i)
# Example usage
exp = "a+b*(c^d-e)^(f+g*h)-i"
obj = Conversion(len(exp))
obj.infixToPostfix(exp)
Output:
abcd^e-fgh*+^*+i-
Result:
Thus the conversion can be successfully executed
Ex.No:6c Application of Queue
Aim:
To implement the application of queue using FCFS CPU Scheduling
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.
5. Stop the program
Coding:
Output:
Processes Burst time Waiting time Turn around time
1 10 0 10
2 5 10 15
3 8 15 23
Result:
Thus the FCFS CPU Scheduling was Executed Successfully
Ex.No:7A Implementation of searching algorithms
Aim:
To implement searching using Linear and Binary Search algorithm using python
Algorithm:
Linear Search:
1. Read the search element from the user
2. Compare, the search element with the first element in the list
3. If both are matching, then display "Given element found!!!" and terminate the function
4. If both are not matching, then compare search element with the next element in the list.
5. Repeat steps 3 and 4 until the search element is compared with the last element in the list.
6. If the last element in the list is also doesn't match, then display "Element not found!!!" and
terminate the function.
Binary search :
1. Read the search element from the user
2. Find the middle element in the sorted list
3. Compare, the search element with the middle element in the sorted list.
4. If both are matching, then display "Given element found!!!" and terminate the function
5. If both are not matching, then check whether the search element is smaller or larger than
middle element
. 6. If the search element is smaller than middle element, then repeat steps 2, 3, 4 and 5 for the
left sublist of the middle element.
7. If the search element is larger than middle element, then repeat steps 2, 3, 4 and 5 for the right
sublist of the middle element.
8. Repeat the same process until we find the search element in the list or until sublist contains
only one element.
9. If that element also doesn't match with the search element, then display "Element not found in
the list!!!" and terminate the function.
# Example usage
arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
key = 40
# Example usage
arr = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
x = 'a'
if result != -1:
print(f"Element '{x}' found at index {result}")
else:
print(f"Element '{x}' not found in the array")
Result:
Thus the implementation of searching using Linear and Binary Search using python was
executed successfully
Ex.No:7B Implementation of Sorting Algorithm
Aim:
To Implement sorting Algorithm using Quick Sort and Insertion Sort algorithm using python
Algorithm:
Quick Sort:
1. Find a “pivot” item in the array. This item is the basis for comparison for a single
round.
2. Start a pointer (the left pointer) at the first item in the array.
3. Start a pointer (the right pointer) at the last item in the array.
4. While the value at the left pointer in the array is less than the pivot value, move the
left pointer to the right (add 1). Continue until the value at the left pointer is greater
than or equal to the pivot value.
5. While the value at the right pointer in the array is greater than the pivot value, move
the right pointer to the left (subtract 1). Continue until the value at the right pointer is
less than or equal to the pivot value.
6. If the left pointer is less than or equal to the right pointer, then swap the values at
these locations in the array.
7. Move the left pointer to the right by one and the right pointer to the left by one.
Insertion Sort:
# Driver code
arr = [2, 5, 3, 8, 6, 5, 4, 7]
n = len(arr)
quickSort(arr, 0, n - 1)
# Driver code
arr = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
insertionSort(arr)
Output:
Quick Sorted array is:
23455678
Result:
Thus the implementation of searching Quick and Insertion Sort algorithm using python was
executed successfully.
Ex.No:8 Implementation of Hash tables
Aim:
To Implement the Hash tables using python
Algorithm:
1. Create a structure, data (hash table item) with key and value as data
2. for loops to define the range within the set of elements.
3. hashfunction(key) for the size of capacity
4. Using insert(),removal() data to be presented or removed.
5. Stop the program
Coding:
# Initialize hash table with empty lists
hashTable = [[] for _ in range(10)]
# Hash function
def hashFunction(key):
return key % 10 # Simple modulus hash function
# Remove a key
removeData(123)
Output:
[[], [], [123, 'apple'], [432, 'mango'], [213, 'banana'], [654, 'guava'], [], [], [], []]
[[], [], 0, [432, 'mango'], [213, 'banana'], [654, 'guava'], [], [], [], []]
Result:
Thus the Implementation of hashing was executed successfully
Ex.No:9a Tree representation
Aim:
To implement tree representation in binary tree format
Algorithm:
1. Create a binary tree.
2. Initially all the left and right vertex are none , then declare the values using insert()
function.3.If data>right element place the element in right
4.If data<left element place the element in left
5.prin the tree
6. Stop the program
Coding:
# Class representing a Node in a Binary Search Tree (BST)
class Node:
def __init__(self, data): # Fixed constructor method
self.left = None
self.right = None
self.data = data
Output:
In-Order Traversal of the BST:
3
6
12
14
Result:
Thus the binary tree representation was successfully created
Ex.No:9b Tree Traversal Algorithms
Preorder(tree)
Visit the root.
Traverse the left subtree, i.e., call Preorder(left-subtree)
Traverse the right subtree, i.e., call Preorder(right-subtree)
Postorder(tree)
Traverse the left subtree, i.e., call Postorder(left-subtree)
Traverse the right subtree, i.e., call Postorder(right-subtree)
Visit the root
Coding:
# Node class representing a single node in a Binary Tree
class Node:
def __init__(self, key): # Fixed constructor
self.left = None
self.right = None
self.val = key
Output:
Preorder traversal of binary tree is
1
2
4
5
3
Inorder traversal of binary tree is
4
2
5
1
3
Postorder traversal of binary tree is
4
5
2
3
1
Result:
Thus the Implementation of traversal using Inorder,Preorder,Postorder techniques was executed
successfully
Ex.No:10 Implementation of Binary Search Trees
Aim:
To Implement the Binary Search Trees using python
Algorithm:
Coding:
class Node:
def __init__(self, data): # Fixed constructor
self.left = None
self.right = None
self.data = data
Output:
7 Not Found
6 is found
Result:
Thus the Implementation of Binary Search Trees using python was executed successfully.
Ex.NO:11 Implementation of Heaps
Aim:
To Implement the Heap algorithm using python
Algorithm:
1. Insert the heap function in the list
2. using heappush(),heappop(),heapify() to insert ,delete,display the elements.
3.Stop the program
Coding:
import heapq
# Initializing list
H = [21, 1, 45, 78, 3, 5]
Output:
Result:
Thus the Implementation of the Heap algorithm was executed succeefully.
Ex.No:12a Graph representation
Aim:
To implement the graph representation using python
Algorithm:
class Graph:
def __init__(self, gdict=None):
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 = []
for vrtx in self.gdict:
for nxtvrtx in self.gdict[vrtx]:
if (nxtvrtx, vrtx) not in edgename and (vrtx, nxtvrtx) not in edgename:
edgename.append((vrtx, nxtvrtx))
return edgename
# Graph representation
graph_elements = {"a": ["b", "c"],"b": ["a", "d"],"c": ["a", "d"],"d": ["e"],"e": ["d"] }
# Printing vertices
print("Vertices:", g.getVertices())
# Printing edges
print("Edges:", g.edges())
Output:
Result:
Thus the implementation of graphs was executed successfully.
Ex.No:12b Graph Traversal
Algorithms Aim:
To Implement using BFS,DFS can be traversed.
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 to the stack.
Step 4 - Repeat step 3 until there is no new vertex to be visited from the vertex which is at the top
of the stack.
Step 5 - When there is no new vertex to visit then use back tracking and pop one vertex from the
stack.
Step 7 - When stack becomes Empty, then produce final spanning tree by removing unused edges
from the graph
BFS:
Step 1 - Define a Queue of size total number of vertices in the graph.
Step 2 - Select any vertex as starting point for traversal. Visit that vertex and insert it into the
Queue.
Step 3 - Visit all the non-visited adjacent vertices of the vertex which is at front of the Queue and
insert them into the Queue.
Step 4 - When there is no new vertex to be visited from the vertex which is at front of the Queue
then delete that vertex.
Step 6 - When queue becomes empty, then produce final spanning tree by removing unused edges
from the graph
Coding:
BFS
import collections
def bfs(graph, root):
visited, queue = set(), collections.deque([root])
visited.add(root)
while queue:
vertex = queue.popleft()
print(str(vertex) + " ", end="")
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
if __name__ == "__main__":
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1, 2] }
print("Following is Breadth First Traversal: ")
bfs(graph, 0)
Output:
Following is Breadth First Traversal:
0123
DFS Coding:
import sys
def ret_graph():
return {
'A': {'B': 5.5, 'C': 2, 'D': 6},
'B': {'A': 5.5, 'E': 3},
'C': {'A': 2, 'F': 2.5},
'D': {'A': 6, 'F': 1.5},
'E': {'B': 3, 'J': 7},
'F': {'C': 2.5, 'D': 1.5, 'K': 1.5, 'G': 3.5},
'G': {'F': 3.5, 'I': 4},
'H': {'J': 2},
'I': {'G': 4, 'J': 4},
'J': {'H': 2, 'I': 4},
'K': {'F': 1.5}
}
start = 'A'
dest = 'J'
visited = []
stack = []
graph = ret_graph()
path = []
stack.append(start)
visited.append(start)
while stack:
curr = stack.pop()
path.append(curr)
if curr == dest:
print("FOUND:", curr)
print("Path:", path)
sys.exit(0) # Exit when the destination is found
print("Not found")
print("Path:", path)
Output:
FOUND: J
['A', 'D', 'F', 'G', 'I']
Result:
Thus the implementation of using BFS,DFS graph can be traversed.
Ex.No:13 Implementation of single source shortest path algorithm
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 of
vertices in given graph.
3) Do following for each edge u-v
If 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-v
If 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
Coding:
from sys import maxsize
# Print results
print("Vertex Distance from Source")
for i in range(V):
print(f"{i}\t\t{dis[i]}")
if __name__ == "__main__":
V = 5 # Number of vertices
E = 8 # Number of edges
graph = [
[0, 1, -1],
[0, 2, 4],
[1, 2, 3],
[1, 3, 2],
[1, 4, 2],
[3, 2, 5],
[3, 1, 1],
[4, 3, -3]
]
BellmanFord(graph, V, E, 0)
OUTPUT
Result:
Thus the Implementation of single source shortest path algorithm was successfully executed.
Ex.No:14 Implementation of minimum spanning tree algorithms
Aim:
To implement the minimum spanning tree algorithms using Kruskal Algorithm
Algorithm:
1. Label each vertex
2. List the edges in non-decreasing order of weight.
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.
5. Continue with step 4 until you have a spanning tree.
Coding:
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
def apply_union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def kruskal_algo(self):
result = [] # Store the final MST
i, e = 0, 0 # Indices for sorted edges and result count
# Step 1: Sort all edges in increasing order of weight
self.graph = sorted(self.graph, key=lambda item:
item[2])
parent = []
rank = []
# Create V subsets with single elements
for node in range(self.V):
parent.append(node)
rank.append(0)
# Number of edges in MST must be V-1
while e < self.V - 1:
u, v, w = self.graph[i]
i += 1
x = self.find(parent, u)
y = self.find(parent, v)
# If including this edge does not cause a cycle, add it
to the result
if x != y:
e += 1
result.append([u, v, w])
self.apply_union(parent, rank, x, y)
# Print the final MST
print("Edges in the Minimum Spanning Tree (MST):")
for u, v, weight in result:
print(f"{u} - {v}: {weight}")
# 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
0 - 1: 4
Result:
Thus the program was executed successfully.
ADDITIONAL PROGRAMS
1. Implementation of Bubble Sort Algorithm:
Aim:
To Implement sorting Algorithm for Bubble Sort using python.
Algorithm:
1. Create a list arr of n elements.
2. Set n to the length of the array.
3. Iterate through the list n times (i from 0 to n-1).
4. For each pass of the outer loop (i):
Compare adjacent elements in the list (arr[j] and arr[j + 1]) for all j from 0 to n-i-2.
If arr[j] > arr[j + 1], swap the two elements.
After each pass, the largest element in the remaining unsorted portion of the array
will bubble up to its correct position.
5. After n-1 passes, the list will be sorted in ascending order.
6. display The sorted list arr.
Coding:
def bubbleSort(arr):
n = len(arr)
for i in range(n):
swapped = False # Track if a swap occurs
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True # A swap happened
# If no elements were swapped, break the loop (array is already sorted)
if not swapped:
break
arr = [2, 1, 10, 23]
bubbleSort(arr)
print("Sorted array is:")
print(arr) # Directly print the sorted array
Output:
Sorted array is :
1
2
10
23
Result:
Thus the program for bubble sort was executed successfully.
2 Implementation of Selection Sort Algorithm:
Aim:
To Implement sorting Algorithm for Selection Sort using python.
Algorithm:
Coding:
Output:
Sorted Array in Ascending Order is:
[1,2,6,7]
Result:
Thus the program for selection sort was executed successfully.
3 Implementation of Merge Sort Algorithm:
Aim:
To Implement sorting Algorithm for Merge Sort using python.
Algorithm:
1. Create a merge_sort() function
2. Initiate array list and divide it into subarrays.
3. Create copies of the subarrays
4. Create three-pointers that maintain indexes.
5. Pick larger elements and place them in the right position
6. Pick the remaining elements and sort them accordingly
7. The result will be sorted array
8. Print the sorted array.
Coding:
def Merge_Sort(array):
if len(array) > 1:
mid = len(array)//2
Left = array[:mid]
Right = array[mid:]
Merge_Sort(Left)
Merge_Sort(Right)
i=j=k=0
while i < len(Left) and j < len(Right):
if Left[i] < Right[j]:
array[k] = Left[i]
i += 1
else:
array[k] = Right[j]
j += 1
k += 1
while i < len(Left):
array[k] = Left[i]
i += 1
k += 1
while j < len(Right):
array[k] = Right[j]
j += 1
k += 1
def printarray(array):
for i in range(len(array)):
print(array[i], end=" ")
print()
if __name__ == '__main__':
array = [7, 2, 5, 6, 3, 1, 8, 4]
print("Orignal Array is: ", array)
Merge_Sort(array)
print("Sorted array is: ")
printarray(array)
Output:
Result:
Aim:
To Implement python program for infix to postfix conversion.
Algorithm:
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, put it in the postfix expression.
3. Otherwise, do the following
If the precedence of the current scanned operator is higher than the precedence of the
operator on top of the stack, or if the stack is empty, or if the stack contains a ‘(‘, then push
the current operator onto the stack.
Else, pop all operators from the stack that have precedence higher than or equal to that of the
current operator. After that push the current operator onto the stack.
4. If the scanned character is a ‘(‘, push it to the stack.
5. If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘ is encountered, and
discard both the parenthesis.
6. Repeat steps 2-5 until the infix expression is scanned.
7. Once the scanning is over, Pop the stack and add the operators in the postfix expression until it
is not empty.
8. Finally, print the postfix expression.
Coding:
def prec(c):
if c == '^':
return 3
elif c == '/' or c == '*':
return 2
elif c == '+' or c == '-':
return 1
else:
return -1
def infixToPostfix(s):
st = []
result = ""
for i in range(len(s)):
c = s[i]
if (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or (c >= '0' and c <= '9'):
result += c
elif c == '(':
st.append('(')
elif c == ')':
while st[-1] != '(':
result += st.pop()
st.pop()
else:
while st and (prec(c) < prec(st[-1]) or prec(c) == prec(st[-1])):
result += st.pop()
st.append(c)
while st:
result += st.pop()
print(result)
exp = "a+b*(c^d-e)^(f+g*h)-i"
infixToPostfix(exp)
Output:
abcd^e-fgh*+^*+i-
Result:
Thus the program for infix to postfix conversion was executed successfully
5 Factorial of a number:
Aim:
To Implement factorial of a number using recursion python
Algorithm:
1. Start
2. Declare a variable n, fact, and i.
3. Now, read the input number given by the user.
4. Initialize variable fact with 1 and i with 1.
5. Repeat until i<=number
Coding:
def factorial(x):
if x == 1 or x == 0:
return 1
else:
return (x * factorial(x-1))
num = 7
# num = int(input("Enter a number: "))
result = factorial(num)
print("The factorial of", num, "is", result)
Output:
Result:
Thus the program for factorial of a number using recursion was executed successfully
6. Sum of natural numbers using recursion:
Aim:
To Implement Sum of natural numbers using recursion using python.
Algorithm:
Coding:
def recurSum(n):
if n <= 1:
return n
return n + recurSum(n - 1)
n=5
print(recurSum(n))
Output
15
Result:
Thus the program for Sum of natural numbers using recursion was executed successfully
7. Python program for dictionary class:
Aim:
To Implement dictionary class using python
Algorithm:
Coding:
class Dictionary:
def __init__(self):
self.data = {}
def add(self, key, value):
self.data[key] = value
print(f"Added {key}: {value}")
def remove(self, key):
if key in self.data:
del self.data[key]
print(f"Removed key: {key}")
else:
print(f"Key '{key}' not found.")
def get(self, key):
return self.data.get(key, "Key not found")
def list_keys(self):
return list(self.data.keys())
def list_values(self):
return list(self.data.values())
def list_key_value_pairs(self):
return list(self.data.items())
def display(self):
if self.data:
print("Current Dictionary:")
for key, value in self.data.items():
print(f"{key}: {value}")
else:
print("Dictionary is empty.")
my_dict = Dictionary()
my_dict.add("name", "John")
my_dict.add("age", 30)
my_dict.add("city", "New York")
my_dict.display()
print("List of Keys:", my_dict.list_keys())
print("List of Values:", my_dict.list_values())
print("List of Key-Value Pairs:", my_dict.list_key_value_pairs())
my_dict.add("country", "USA")
my_dict.display()
Output:
Added name: John
Added age: 30
Added city: New York
Current Dictionary:
name: John
age: 30
city: New York
List of Keys: ['name', 'age', 'city']
List of Values: ['John', 30, 'New York']
List of Key-Value Pairs: [('name', 'John'), ('age', 30), ('city', 'New York')]
Added country: USA
Current Dictionary:
name: John
age: 30
city: New York
country: USA
Result:
Aim:
To Implement python program for max heap .
Algorithm:
Coding:
Result:
Aim:
To Implement python program for min heap .
Algorithm:
Coding:
from heapq import heapify, heappush, heappop
heap = []
heapify(heap)
heappush(heap, 10)
heappush(heap, 30)
heappush(heap, 20)
heappush(heap, 400)
print("Head value of heap : "+str(heap[0]))
print("The heap elements : ")
for i in heap:
print(i, end = ' ')
print("\n")
element = heappop(heap)
print("The heap elements : ")
for i in heap:
print(i, end = ' ')
Output:
Head value of heap : 10
The heap elements :
10 30 20 400
The heap elements :
20 30 400
Result: