PP & Dsa Journal
PP & Dsa Journal
LAB JOURNAL
OF
MCA-I (SEM-I)
MCA-I (SEM-I)
A
Lab Journal
Of
By
CERTIFICATE
Date:
This is to certify that Mr. Rizwanuddin Nizamuddin Khan. Student of the class MCA-I (SEM-I)
has successfully completed the Practical Journal on “IT-11 & IT-12 Practical” (Python
Programming & Data Structure & Algorithms) during the academic year 2024-2025.
3
Program Index
Sr. Page
Program
No. No.
Write a Python program to accept n numbers in list and remove Duplicates
1 6
from a list.
Write a Python program to check if a given key already exists in a dictionary. If
2 7
key exists replace with another key/value pair
Write a python script to define a class student having members roll no, name,
age, gender. Create a subclass called Test with member marks of 3 subjects.
3 8
Create three objects of the Test class and display all the details of the student
with total marks.
4 Write Python GUI program to create background with changing colors 10
Write Python class to perform addition of two complex numbers using binary +
5 11
operator overloading.
Write python GUI program to generate a random password with upper and
6 13
lowercase letters.
7 Write a Python script using class to reverse a string word by word 15
Write a Python class named Student with two attributes student_name, marks.
11 Modify the attribute values of the said class and print the original and modified 19
values of the said attributes.
Write Python GUI program to add items in listbox widget and to print and
12 delete the selected items from list box onbuttonclick. Provide three separate 20
buttons to add, print and delete
Create a list a=[1,1,2,3,5,8,13,21,34,55,89] and write a python program that
13 22
prints out all the elements of the list are less than5
Write a Python GUI program to accept a number form user and display its
14 23
multiplication table onbuttonclick
Write a python program to create a class Circle and Compute the Area and the
15 25
circumferences of the circle.(useparameterized constructor)
Write a Python program to convert a tuple of string values to a tuple of integer
16 values. Original tuple values: ((' 333',' 33'),(' 1416','55')) New tuple values: 26
((333,33), (1416,55))
4
17
Write an anonymous function to find area of square and rectangle. 27
Write Python GUI program which accepts a sentence from the user and alters it
18 when a button is pressed. Every space should be replaced by *,case of all 28
alphabets should be reversed, digits are replaced by?
19
Write a Python program to unzip a list of tuples into individual lists 30
Write Python GUI program to accept a decimal number and convert and
20 32
display it to binary, octal and hexadecimal number
Q.1 Write a Python program to accept n numbers in list and remove Duplicates from a list.
marks=[]
n=int(input('Enternumberofelements:'))
for i in range(n):
value=int(input())
5
marks.append(value)
print(marks)
new_marks=[]
for x in marks:
if x not in new_marks:
new_marks.append(x)
print(new_marks)
Output –
Enternumberofelements:5
1
2
3
4
5
[1, 2, 3, 4, 5]
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
Q.2 Write a Python program to check if a given key already exists in a dictionary. If key exists replace
with another key/value pair
data_dict = {}
n = int(input("Enter the number of keys: "))
for _ in range(n):
while True:
key = input("Enter a unique key: ")
6
if key in data_dict:
print("The given key already exists! Keys so far:", ", ".join(data_dict.keys()))
print("^ Please use a different key from the list above.")
else:
break
value = input("Enter the value: ")
data_dict[key] = value
print("Final Dictionary:", data_dict)
Output –
Enter the number of keys: 1
Enter a unique key: abc
Enter the value: 2803
Final Dictionary: {'abc': '2803'}
Q.3 Write a python script to define a class student having members roll no, name, age, gender. Create
a subclass called Test with member marks of 3 subjects. Create three objects of the Test class and
display all the details of the student with total marks.
Output –
Name: Alice
Roll No: 101
Age: 20
Gender: Female
Total Marks: 263
Name: Bob
Roll No: 102
Age: 21
Gender: Male
Total Marks: 239
Name: Charlie
Roll No: 103
Age: 19
Gender: Male
8
Total Marks: 270
Q.4 Write Python GUI program to create background with changing colors
from tkinter import Button, Entry, Label, Tk
Output –
Q.5 Write Python class to perform addition of two complex numbers using binary + operator
overloading.
class Complex:
# Constructor to initialize complex numbers
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
10
# Overloading the '+' operator for complex number addition
def __add__(self, other):
return Complex(self.real + other.real, self.imag + other.imag)
# Display results
print("\nFirst Complex Number:", end=" ")
c1.display()
Output –
Enter the first complex number:
Enter the real part: 5
Enter the imaginary part: 2
11
Q.6 Write python GUI program to generate a random password with upper and lowercase letters.
import string
import random
from tkinter import *
# Main code
if __name__ == "__main__":
# Create the main GUI window
gui = Tk()
gui.configure(background="lightgreen")
gui.title("Random Password Generator")
gui.geometry("325x150")
13
Q.7 Write a Python script using class to reverse a string word by word
14
def reverse_string(string):
str1 = "" # Declaring an empty string to store the reversed string
for i in string:
str1 = i + str1
return str1 # It will return the reversed string to the caller function
# Given String
string = "python"
print("The original string is:", string)
print("The reversed string is:", reverse_string(string)) # Function call
Output –
The original string is: python
The reversed string is: nohtyp
Q.8 Write Python GUI program to display an alert message when a button is pressed. Import tkinter.
Messagebox
15
import tkinter
import tkinter.messagebox
Output –
Q.9 Write a Python class to find validity of a string of parentheses,' (',' '}' ,'['' ]{}" )',' {', ]’.These
brackets must be close in the correct order. For example "()"and"()[ ]{}” are valid but “[)”, “({[)]”
and “{{{“ are invalid.
class Validity:
16
@staticmethod
def is_balanced(s):
stack = []
mapping = {')': '(', '}': '{', ']': '['} # Mapping closing to opening brackets
for char in s:
if char in mapping: # If the character is a closing bracket
top_element = stack.pop() if stack else '#' # Pop the top of the stack or use a dummy value
if mapping[char] != top_element: # Check for mismatch
return False
else:
stack.append(char) # Push opening brackets onto the stack
Output –
Enter a string of parentheses: ()
() - is Balanced
# Given tuples
x = (1, 2, 3, 4)
y = (3, 5, 2, 1)
17
z = (2, 2, 3, 1)
Output –
Original tuples:
x: (1, 2, 3, 4)
y: (3, 5, 2, 1)
z: (2, 2, 3, 1)
Q.11 Write a Python class named Student with two attributes student_name, marks. Modify the
attribute values of the said class and print the original and modified values of the said attributes.
class Student:
# Constructor to initialize attributes
def __init__(self, student_name, marks):
18
self.student_name = student_name
self.marks = marks
Output –
Original Name and Marks:
Name: Abc, Marks: 81
Enter modified name: Tejas
Enter modified marks: 89
Q.12 Write Python GUI program to add items in listbox widget and to print and delete the selected
items from list box onbuttonclick. Provide three separate buttons to add, print and delete
# Listbox widget
listbox = Listbox(root, selectmode=MULTIPLE, width=30, height=10)
listbox.pack(pady=5)
20
# Execute Tkinter main loop
root.mainloop()
Output –
Q.13 Create a list a=[1,1,2,3,5,8,13,21,34,55,89] and write a python program that prints out all the
elements of the list are less than 5
# Original list
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
21
# Filter the list into two separate lists
less_than_n = [i for i in a if i < n] # List of elements less than n
greater_or_equal_n = [i for i in a if i >= n] # List of elements greater than or equal to n
Output –
Enter a number to filter the list: 2
Original list: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Elements less than 2: [1, 1]
Elements greater than or equal to 2: [2, 3, 5, 8, 13, 21, 34, 55, 89]
Q.14 Write a Python GUI program to accept a number form user and display its multiplication table
onbuttonclick
# Main GUI
if __name__ == "__main__":
gui = Tk()
gui.configure(background="lightgreen")
gui.title("Multiplication Table")
gui.geometry("400x400")
# Title label
Label(gui, text="Multiplication Table", bg="lightgreen", font=("Arial", 16)).pack(pady=10)
Output –
23
Q.15 Write a python program to create a class Circle and Compute the Area and the circumferences
of the circle.(use parameterized constructor)
class Circle:
def __init__(self, radius):
"""Parameterized constructor to initialize the radius of the circle"""
self.radius = radius
24
def area(self):
"""Calculate and return the area of the circle"""
return round(pi * self.radius ** 2, 2)
def circumference(self):
"""Calculate and return the circumference of the circle"""
return round(2 * pi * self.radius, 2)
Output –
Enter the radius of the circle: 5
Area of the circle: 78.54
Circumference of the circle: 31.42
Q.16 Write a Python program to convert a tuple of string values to a tuple of integer values. Original
tuple values: ((' 333',' 33'),(' 1416','55')) New tuple values:((333,33), (1416,55))
Output –
Original tuple values: (('333', '33'), ('1416', '55'))
New tuple values: ((333, 33), (1416, 55))
Output –
Enter the side value of square: 4
Area of square: 16
Enter the length value of rectangle: 12
Enter the width value of rectangle: 10
Area of rectangle: 120
Q.18 Write Python GUI program which accepts a sentence from the user and alters it when a button
is pressed. Every space should be replaced by *,case of all alphabets should be reversed, digits are
replaced by?
def clearAll():
str1Field.delete(0, END)
altersField.delete(0, END)
def checkError():
27
if(str1Field.get() == ""):
messagebox.showerror("Input Error", "Please enter a string.")
clearAll()
return -1
return 0
def occurrences():
value = checkError()
if value == -1:
return
else:
String0 = str1Field.get()
newstr = ''
for char in String0:
if char.isupper(): # If character is uppercase
char = char.lower()
newstr += char
elif char.islower(): # If character is lowercase
char = char.upper()
newstr += char
elif char == ' ': # If character is space
char = '*'
newstr += char
elif char.isdigit(): # If character is a digit
char = '?'
newstr += char
else:
newstr += char
if __name__ == "__main__":
gui = Tk()
gui.configure(background="lightgreen")
gui.title("Alter String")
gui.geometry("300x200")
gui.mainloop()
Output –
Q.19 Write a Python program to unzip a list of tuples into individual lists
l=[(1,2),(3,4),(8,9)]
print(list(zip(*l)))
Output –
[(1, 3, 8), (2, 4, 9)]
Q.20 Write Python GUI program to accept a decimal number and convert and display it to binary,
octal and hexadecimal number
if __name__ == "__main__":
# Set up the GUI window
gui = Tk()
gui.configure(background="lightgreen")
gui.title("Decimal Number Converter")
gui.geometry("400x300")
resultLabel.grid(row=2, column=1)
resultButton.grid(row=3, column=1)
binaryLabel.grid(row=4, column=0)
binaryField.grid(row=5, column=0)
octalLabel.grid(row=4, column=1)
octalField.grid(row=5, column=1)
hexadecimalLabel.grid(row=4, column=2)
hexadecimalField.grid(row=5, column=2)
clearButton.grid(row=6, column=1)
Output –
31
Program Index
Sr. Page
Program
No. No.
2 STACK implementation using Array with PUSH, POP operations using Python 38
32
Programming
3 Reverse a string using stack using Python Programming 40
10
Practical based on binary search tree implementation with its operations 53
13
Write a program in python for merge sort 59
15
Write a program in python for bubble sort 62
16
Write a program of heap sort using python 63
Q.1 Demonstrate singly and doubly linked list using Python Programming
def display(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
Output :
Singly Linked List:
1 -> 2 -> 3 -> None
1 -> 3 -> None
35
class DoublyLinkedList:
def __init__(self):
self.head = None
def display(self):
current = self.head
print("Forward: ", end="")
while current:
print(current.data, end=" <-> ")
last = current
current = current.next
print("None")
# Reverse traversal
print("Backward: ", end="")
while last:
print(last.data, end=" <-> ")
last = last.prev
print("None")
36
# Demonstrate Doubly Linked List
print("\nDoubly Linked List:")
dll = DoublyLinkedList()
dll.append(10)
dll.append(20)
dll.append(30)
dll.display()
dll.delete(20)
dll.display()
Output -
Doubly Linked List:
Forward: 10 <-> 20 <-> 30 <-> None
Backward: 30 <-> 20 <-> 10 <-> None
Forward: 10 <-> 30 <-> None
Backward: 30 <-> 10 <-> None
Q.2 STACK implementation using Array with PUSH, POP operations using Python Programming
class Stack:
def __init__(self):
self.stack = []
def peek(self):
"""Return the top item without removing it."""
if self.is_empty():
print("Stack is empty.")
return None
return self.stack[-1]
def is_empty(self):
"""Check if the stack is empty."""
return len(self.stack) == 0
def display(self):
"""Display the current stack."""
if self.is_empty():
print("Stack is empty.")
else:
print("Stack contents (top to bottom):", self.stack[::-1])
# Demonstration of Stack
stack = Stack()
print("Stack Operations:")
stack.push(10)
stack.push(20)
stack.push(30)
stack.display()
stack.pop()
stack.display()
stack.pop()
stack.pop()
stack.pop() # Attempting to pop from an empty stack
Output –
Stack Operations:
Pushed: 10
38
Pushed: 20
Pushed: 30
Stack contents (top to bottom): [30, 20, 10]
Popped: 30
Stack contents (top to bottom): [20, 10]
Popped: 20
Popped: 10
Stack Underflow! Cannot pop from an empty stack.
def reverse_string_with_stack(input_string):
# Initialize an empty stack
stack = []
# Pop characters from the stack and append to the reversed string
reversed_string = ""
39
while stack:
reversed_string += stack.pop()
return reversed_string
Output -
Original String: hello
Reversed String: olleh
Q.4 Check for balanced parentheses by using Stacks using Python Programming
def is_balanced(expression):
# Stack to keep track of opening brackets
stack = []
Output –
Expression: () -> Balanced: True
Expression: (] -> Balanced: False
Expression: ([{}]) -> Balanced: True
Expression: ((()) -> Balanced: False
Expression: ([)] -> Balanced: False
Expression: {[()]} -> Balanced: True
class Node:
"""Node class for the linked list."""
def __init__(self, data):
self.data = data
self.next = None
class Stack:
"""Stack implementation using a linked list."""
def __init__(self):
self.top = None # Represents the top of the stack
def pop(self):
"""Remove and return the top element of the stack."""
if self.is_empty():
print("Stack Underflow! Cannot pop from an empty stack.")
return None
popped_data = self.top.data
self.top = self.top.next
print(f"Popped: {popped_data}")
return popped_data
def peek(self):
"""Return the top element without removing it."""
if self.is_empty():
print("Stack is empty.")
return None
return self.top.data
def is_empty(self):
"""Check if the stack is empty."""
return self.top is None
def display(self):
"""Display the current stack."""
if self.is_empty():
print("Stack is empty.")
else:
current = self.top
print("Stack contents (top to bottom):", end=" ")
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
stack.peek()
stack.pop()
stack.pop()
stack.pop() # Attempt to pop from an empty stack
Output –
Stack Operations:
Pushed: 10
Pushed: 20
Pushed: 30
Stack contents (top to bottom): 30 -> 20 -> 10 -> None
Popped: 30
Stack contents (top to bottom): 20 -> 10 -> None
Popped: 20
Popped: 10
Stack Underflow! Cannot pop from an empty stack.
class LinearQueue:
def __init__(self, size):
"""Initialize the queue with a fixed size."""
self.queue = [None] * size # Fixed-size list to represent the queue
self.front = -1 # Points to the front of the queue
self.rear = -1 # Points to the rear of the queue
self.size = size
def is_empty(self):
"""Check if the queue is empty."""
return self.front == -1
def is_full(self):
"""Check if the queue is full."""
43
return self.rear == self.size - 1
def dequeue(self):
"""Remove and return the front item of the queue."""
if self.is_empty():
print("Queue Underflow! Cannot dequeue.")
return None
item = self.queue[self.front]
self.queue[self.front] = None
if self.front == self.rear: # Queue becomes empty after this operation
self.front = self.rear = -1
else:
self.front += 1
print(f"Dequeued: {item}")
return item
def display(self):
"""Display the current queue."""
if self.is_empty():
print("Queue is empty.")
else:
print("Queue contents:", self.queue[self.front:self.rear + 1])
queue.dequeue()
queue.display()
queue.enqueue(40)
44
queue.enqueue(50)
queue.enqueue(60) # Attempt to enqueue when the queue is full
queue.display()
queue.dequeue()
queue.dequeue()
queue.dequeue()
queue.dequeue() # Attempt to dequeue from an empty queue
Output
Queue Operations:
Enqueued: 10
Enqueued: 20
Enqueued: 30
Queue contents: [10, 20, 30]
Dequeued: 10
Queue contents: [20, 30]
Enqueued: 40
Enqueued: 50
Queue Overflow! Cannot enqueue.
Queue contents: [20, 30, 40, 50]
Dequeued: 20
Dequeued: 30
Dequeued: 40
Dequeued: 50
Queue Underflow! Cannot dequeue.
class CircularQueue:
def __init__(self, size):
"""Initialize the circular queue with a fixed size."""
self.queue = [None] * size
self.front = -1 # Points to the front of the queue
self.rear = -1 # Points to the rear of the queue
self.size = size
def is_empty(self):
"""Check if the queue is empty."""
return self.front == -1
def is_full(self):
"""Check if the queue is full."""
return (self.rear + 1) % self.size == self.front
45
def enqueue(self, item):
"""Add an item to the rear of the queue."""
if self.is_full():
print("Queue Overflow! Cannot enqueue.")
return
if self.front == -1: # First insertion
self.front = 0
self.rear = (self.rear + 1) % self.size
self.queue[self.rear] = item
print(f"Enqueued: {item}")
def dequeue(self):
"""Remove and return the front item of the queue."""
if self.is_empty():
print("Queue Underflow! Cannot dequeue.")
return None
item = self.queue[self.front]
self.queue[self.front] = None
if self.front == self.rear: # Queue becomes empty after this operation
self.front = self.rear = -1
else:
self.front = (self.front + 1) % self.size
print(f"Dequeued: {item}")
return item
def display(self):
"""Display the current queue."""
if self.is_empty():
print("Queue is empty.")
else:
print("Queue contents:", end=" ")
i = self.front
while True:
print(self.queue[i], end=" ")
if i == self.rear:
break
i = (i + 1) % self.size
print()
queue.dequeue()
queue.dequeue()
queue.display()
queue.enqueue(50)
queue.enqueue(60)
queue.enqueue(70) # Enqueue wraps around
queue.display()
queue.dequeue()
queue.dequeue()
queue.display()
Output –
Circular Queue Operations:
Enqueued: 10
Enqueued: 20
Enqueued: 30
Enqueued: 40
Queue contents: 10 20 30 40
Dequeued: 10
Dequeued: 20
Queue contents: 30 40
Enqueued: 50
Enqueued: 60
Enqueued: 70
Queue contents: 30 40 50 60 70
Dequeued: 30
Dequeued: 40
Queue contents: 50 60 70
47
Q.8 Demonstration of Priority Queue using Python
import heapq
class PriorityQueue:
def __init__(self):
"""Initialize an empty priority queue."""
self.queue = [] # A list to store queue elements
def dequeue(self):
"""Remove and return the highest priority element."""
if self.is_empty():
print("Queue Underflow! Cannot dequeue.")
return None
priority, item = heapq.heappop(self.queue)
print(f"Dequeued: {item} with priority {priority}")
48
return item
def peek(self):
"""Return the highest priority element without removing it."""
if self.is_empty():
print("Queue is empty.")
return None
priority, item = self.queue[0]
return item
def is_empty(self):
"""Check if the priority queue is empty."""
return len(self.queue) == 0
def display(self):
"""Display the contents of the priority queue."""
if self.is_empty():
print("Queue is empty.")
else:
print("Priority Queue contents (priority, item):", self.queue)
pq.dequeue()
pq.display()
pq.enqueue("Task D", 1)
pq.display()
pq.dequeue()
pq.dequeue()
pq.dequeue()
pq.dequeue() # Attempt to dequeue from an empty queue
Output-
Priority Queue Operations:
Enqueued: Task A with priority 3
Enqueued: Task B with priority 1
Enqueued: Task C with priority 2
Priority Queue contents (priority, item): [(1, 'Task B'), (3, 'Task A'), (2, 'Task C')]
49
Dequeued: Task B with priority 1
Priority Queue contents (priority, item): [(2, 'Task C'), (3, 'Task A')]
Enqueued: Task D with priority 1
Priority Queue contents (priority, item): [(1, 'Task D'), (3, 'Task A'), (2, 'Task C')]
Dequeued: Task D with priority 1
Dequeued: Task C with priority 2
Dequeued: Task A with priority 3
Queue Underflow! Cannot dequeue.
class Stack:
"""Stack implementation using a list."""
def __init__(self):
self.stack = []
def pop(self):
"""Pop an item from the stack."""
if not self.is_empty():
return self.stack.pop()
else:
print("Stack Underflow! Cannot pop.")
return None
def is_empty(self):
"""Check if the stack is empty."""
50
return len(self.stack) == 0
def display(self):
"""Display the current stack."""
print("Stack contents (top to bottom):", self.stack[::-1])
def reverse_stack(stack):
"""Reverse the stack using a queue."""
q = Queue()
# Demonstration
print("Original Stack:")
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.display()
print("\nReversed Stack:")
stack.display()
Output –
Original Stack:
Stack contents (top to bottom): [4, 3, 2, 1]
Reversed Stack:
Stack contents (top to bottom): [1, 2, 3, 4]
51
Q.10 Practical based on binary search tree implementation with its operations
class Node:
"""Class representing a node in the Binary Search Tree."""
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class BinarySearchTree:
"""Class for the Binary Search Tree."""
def __init__(self):
self.root = None
def in_order(self):
"""In-order traversal of the BST."""
result = []
self._in_order(self.root, result)
return result
def pre_order(self):
"""Pre-order traversal of the BST."""
result = []
self._pre_order(self.root, result)
return result
def post_order(self):
"""Post-order traversal of the BST."""
result = []
self._post_order(self.root, result)
return result
# Insertions
54
print("Inserting keys: 50, 30, 70, 20, 40, 60, 80")
bst.insert(50)
bst.insert(30)
bst.insert(70)
bst.insert(20)
bst.insert(40)
bst.insert(60)
bst.insert(80)
# Traversals
print("\nIn-order Traversal (sorted order):", bst.in_order())
print("Pre-order Traversal:", bst.pre_order())
print("Post-order Traversal:", bst.post_order())
# Search
print("\nSearching for key 40:", bst.search(40))
print("Searching for key 100:", bst.search(100))
# Deletion
print("\nDeleting key 20 (leaf node)")
bst.delete(20)
print("In-order Traversal:", bst.in_order())
Output-
Inserting keys: 50, 30, 70, 20, 40, 60, 80
In-order Traversal (sorted order): [20, 30, 40, 50, 60, 70, 80]
Pre-order Traversal: [50, 30, 20, 40, 70, 60, 80]
Post-order Traversal: [20, 40, 30, 60, 80, 70, 50]
if result != -1:
print(f"Element {target} found at index {result}.")
else:
print(f"Element {target} not found in the list.")
Output –
Element 30 found at index 2.
56
Q.12 Write a program in python for binary search
if result != -1:
print(f"Element {target} found at index {result}.")
else:
print(f"Element {target} not found in the list.")
57
Output –
Element 40 found at index 3.
def merge_sort(arr):
"""Sort the array using merge sort algorithm."""
if len(arr) <= 1:
return arr
# Compare elements of left and right and merge them in sorted order
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
58
j += 1
return result
sorted_arr = merge_sort(arr)
print("Sorted array:", sorted_arr)
Q.14 Implement quick sort using python
def quick_sort(arr):
"""Sort the array using the quick sort algorithm."""
if len(arr) <= 1:
return arr
else:
# Choose a pivot element (here, the last element is used as pivot)
pivot = arr[-1]
# Recursively apply quick sort to both halves and concatenate with pivot
return quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot)
sorted_arr = quick_sort(arr)
print("Sorted array:", sorted_arr)
Output –
Original array: [38, 27, 43, 3, 9, 82, 10]
Sorted array: [3, 9, 10, 27, 38, 43, 82]
59
Q.15 Write a program in python for bubble sort
def bubble_sort(arr):
"""Sort the array using bubble sort algorithm."""
n = len(arr)
for i in range(n):
# Flag to detect if any swapping happens
swapped = False
for j in range(0, n-i-1): # Last i elements are already sorted
if arr[j] > arr[j+1]:
# Swap if the element is greater than the next element
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
# If no two elements were swapped in the inner loop, the array is sorted
if not swapped:
break
return arr
sorted_arr = bubble_sort(arr)
print("Sorted array:", sorted_arr)
Output –
Original array: [64, 34, 25, 12, 22, 11, 90]
Sorted array: [11, 12, 22, 25, 34, 64, 90]
60
Q.16 Write a program of heap sort using python
61
# Example usage
arr = [12, 11, 13, 5, 6, 7]
print("Original array:", arr)
heap_sort(arr)
Output –
Original array: [12, 11, 13, 5, 6, 7]
Sorted array: [5, 6, 7, 11, 12, 13]
Q.17 Implementation of conversion of an expression (Infix Prefix Postfix) using python programming
while stack:
postfix.append(stack.pop())
return ''.join(postfix)
# Example usage:
infix = "A+B*(C-D)"
print(f"Infix Expression: {infix}")
print(f"Postfix Expression: {infix_to_postfix(infix)}")
print(f"Prefix Expression: {infix_to_prefix(infix)}")
Output –
Infix Expression: A+B*(C-D)
Postfix Expression: ABCD-*+
Prefix Expression: +A*B-CD
63
Q.18 Write a program of sparse matrix using python programming
class SparseMatrix:
def __init__(self, rows, cols):
# Initialize the sparse matrix with the given dimensions
self.rows = rows
self.cols = cols
self.matrix = {}
return result
return result
# Example usage:
print("\nMatrix B:")
B.display()
Output –
Matrix A:
Sparse Matrix (only non-zero elements):
Position (0, 0) -> 5
Position (1, 1) -> 8
Position (2, 2) -> 3
Matrix B:
Sparse Matrix (only non-zero elements):
Position (0, 2) -> 7
Position (1, 0) -> 6
Position (2, 1) -> 4
Matrix A + B:
Sparse Matrix (only non-zero elements):
Position (0, 0) -> 5
Position (1, 1) -> 8
Position (2, 2) -> 3
Position (0, 2) -> 7
Position (1, 0) -> 6
Position (2, 1) -> 4
Matrix A * B:
Sparse Matrix (only non-zero elements):
Position (0, 2) -> 35
Position (1, 0) -> 48
Position (2, 1) -> 12
66
Q.19 Write a program of reverse of a string using python programming (Don’t use inbuilt function)
def reverse_string(s):
reversed_str = ""
# Loop through the string from the end to the beginning
for i in range(len(s) - 1, -1, -1):
reversed_str += s[i]
return reversed_str
# Example usage
input_string = "Hello, World!"
reversed_string = reverse_string(input_string)
Output –
Original String: Hello, World!
Reversed String: !dlroW ,olleH
67
Q.20 Write a program to find out age (year,month,days) in this program read current Date and
birthdate and find out how old are you?
if months < 0:
years -= 1
months += 12
# Main function
def main():
# Get the current date and birthdate from user input
birthdate = get_date_input("Enter your birthdate (YYYY-MM-DD): ")
print(f"You are {years} years, {months} months, and {days} days old.")
68
# Run the program
if __name__ == "__main__":
main()
Output – Enter your birthdate (YYYY-MM-DD): 2004-03-28
You are 20 years, 8 months, and 5 days old.
69