0% found this document useful (0 votes)
35 views69 pages

PP & Dsa Journal

Uploaded by

reactantfactory
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views69 pages

PP & Dsa Journal

Uploaded by

reactantfactory
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

SAVITRIBAI PHULE PUNE UNIVERSITY

MASTER OF COMPUTER APPLICATION

Dr. D.Y. Patil Centre of Management & Research


(MCA)
Chikhali, Pune-412114

LAB JOURNAL

OF

PYTHON PROGRAMMING & DATA


STRUCTURE & ALGORITHMS

Course Code: IT-11 & IT-12

MCA-I (SEM-I)

Academic Year 2024-2025


Shikshan Maharshi Dr. D.Y.Patil Shikshan Sanstha’s
Dr. D.Y. Patil Centre for Management & Research
Newale Vasti, Chikhali, Pune- 412114

MCA-I (SEM-I)

A
Lab Journal
Of

PYTHON PROGRAMMING & DATA STRUCTURE &


ALGORITHMS

By

Rizwanuddin Nizamuddin Khan

Submitted in partial fulfillment of


First Year Master in Computer Application
Savitribai Phule Pune University

Under The Guidance Of

Prof. Shubhangi Shinde & Dr. Prashant Chordiya

Dr. D.Y. Patil Centre for Management & Research (MCA)


Newale Vasti, Chikhali, Dist- Pune-412114

Department of MCA, A. Y. 2024-25


Shikshan Maharshi Dr. D.Y.Patil Shikshan Sanstha’s
Dr. D.Y. Patil Centre for Management & Research
Newale Vasti, Chikhali, Pune- 412114

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.

Prof. Shubhangi Shinde Dr. Jayshri Patil Dr. Sunil Dhanawade


Dr. Prashant Chordiya

Subject Coordinator HOD, DYPCMR Director DYPCMR

Exam Seat No: Internal Examiner External Examiner

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 Python GUI program to display an alert message when a button is


8 16
pressed. Import tkinter. messagebox
Write a Python class to find validity of a string of parentheses,' (',' '}' ,'['' ]{}" )','
9 {', ]’.These brackets must be close in the correct order. For example "()"and"() 17
[ ]{}” are valid but “[)”, “({[)]” and “{{{“ are invalid.
10
Write a Python program to compute element-wise sum of given tuples 18

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.

# Define the Student class


class Student:
def __init__(self, roll_no, name, age, gender):
self.roll_no = roll_no
self.name = name
self.age = age
7
self.gender = gender

# Define the Test subclass inheriting from Student


class Test(Student):
def __init__(self, roll_no, name, age, gender, sub1_mark, sub2_mark, sub3_mark):
super().__init__(roll_no, name, age, gender)
self.mark1 = sub1_mark
self.mark2 = sub2_mark
self.mark3 = sub3_mark

# Method to calculate and display total marks


def get_marks(self):
self.total = self.mark1 + self.mark2 + self.mark3
print(f"Name: {self.name}")
print(f"Roll No: {self.roll_no}")
print(f"Age: {self.age}")
print(f"Gender: {self.gender}")
print(f"Total Marks: {self.total}\n")

# Create three objects of the Test class


student1 = Test(101, "Alice", 20, "Female", 85, 90, 88)
student2 = Test(102, "Bob", 21, "Male", 78, 82, 79)
student3 = Test(103, "Charlie", 19, "Male", 92, 87, 91)

# Display details for each student


student1.get_marks()
student2.get_marks()
student3.get_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

# Function to change the background color


def change_color():
new_value = value.get() # Get the color entered by the user
gui.configure(background=new_value) # Update the background color

# Create the main GUI window


gui = Tk()
gui.title("Background Color Changer")
gui.configure(background="gray")
9
gui.geometry("400x300")

# Add a label to prompt user for color


color_label = Label(gui, text="Enter Color:", bg="gray", fg="black")
color_label.grid(row=0, column=0, padx=10, pady=10)

# Add an entry field for user to input the color


value = Entry(gui)
value.grid(row=0, column=1, padx=10, pady=10)

# Add a button to apply the color change


apply_button = Button(gui, text="Apply", command=change_color, bg="lightblue", fg="black")
apply_button.grid(row=0, column=2, padx=10, pady=10)

# Run the GUI loop


gui.mainloop()

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

# Method to display a complex number


def display(self):
print(f"{self.real} + {self.imag}i")

10
# Overloading the '+' operator for complex number addition
def __add__(self, other):
return Complex(self.real + other.real, self.imag + other.imag)

# Input and display for two complex numbers


print("Enter the first complex number:")
real1 = int(input("Enter the real part: "))
imag1 = int(input("Enter the imaginary part: "))

print("\nEnter the second complex number:")


real2 = int(input("Enter the real part: "))
imag2 = int(input("Enter the imaginary part: "))

# Create complex number objects


c1 = Complex(real1, imag1)
c2 = Complex(real2, imag2)

# Perform addition using the overloaded '+' operator


c3 = c1 + c2

# Display results
print("\nFirst Complex Number:", end=" ")
c1.display()

print("Second Complex Number:", end=" ")


c2.display()

print("Sum of the two Complex Numbers:", end=" ")


c3.display()

Output –
Enter the first complex number:
Enter the real part: 5
Enter the imaginary part: 2

Enter the second complex number:


Enter the real part: 5
Enter the imaginary part: 3

First Complex Number: 5 + 2i


Second Complex Number: 5 + 3i
Sum of the two Complex Numbers: 10 + 5i

11
Q.6 Write python GUI program to generate a random password with upper and lowercase letters.

import string
import random
from tkinter import *

# Function to generate a random password


def generate_password():
# Clear the current password field
clear_all()
# Generate a random password
characters = random.sample(string.ascii_letters, 6) + random.sample(string.digits, 4)
random.shuffle(characters) # Shuffle the characters for randomness
password = ''.join(characters) # Join characters to form the password
12
pass_field.insert(0, password) # Display the password in the entry field

# Function to clear the password field


def clear_all():
pass_field.delete(0, END)

# Main code
if __name__ == "__main__":
# Create the main GUI window
gui = Tk()
gui.configure(background="lightgreen")
gui.title("Random Password Generator")
gui.geometry("325x150")

# Label for password


Label(gui, text="Generated Password:", bg="#00ffff").pack(pady=5)

# Entry field to display the password


pass_field = Entry(gui, width=30, justify='center')
pass_field.pack(pady=5)

# Button to generate password


Button(gui, text="Generate Password", fg="Black", bg="gray",
command=generate_password).pack(pady=5)

# Button to clear the entry field


Button(gui, text="Clear", fg="Black", bg="Red", command=clear_all).pack(pady=5)

# Run the GUI event loop


gui.mainloop()
Output –

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

# Function to display an alert message


def onClick():
tkinter.messagebox.showinfo("Alert", "Button Pressed!")

# Create the main GUI window


root = tkinter.Tk()
root.title("Alert Message Example")
root.geometry("200x100")

# Add a button that triggers the alert


button = tkinter.Button(root, text="Click Me", command=onClick)
button.pack(pady=20)

# Run the GUI event loop


root.mainloop()

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

return not stack # If the stack is empty, the string is balanced

# Input from the user


s = input("Enter a string of parentheses: ")

# Check if the string is balanced


if Validity.is_balanced(s):
print(f"{s} - is Balanced")
else:
print(f"{s} - is Unbalanced")

Output –
Enter a string of parentheses: ()
() - is Balanced

Q.10 Write a Python program to compute element-wise sum of given tuples

# Given tuples
x = (1, 2, 3, 4)
y = (3, 5, 2, 1)
17
z = (2, 2, 3, 1)

# Display the original tuples


print("Original tuples:")
print("x:", x)
print("y:", y)
print("z:", z)

# Compute element-wise sum of the tuples


result = tuple(map(sum, zip(x, y, z)))

# Display the result


print("\nElement-wise sum of the said tuples:")
print(result)

Output –
Original tuples:
x: (1, 2, 3, 4)
y: (3, 5, 2, 1)
z: (2, 2, 3, 1)

Element-wise sum of the said tuples:


(6, 9, 8, 6)

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

# Method to display the original name and marks


def get_details(self):
print("\nOriginal Name and Marks:")
print(f"Name: {self.student_name}, Marks: {self.marks}")

# Method to modify the student's details


def modify_details(self):
self.student_name = input("Enter modified name: ")
self.marks = int(input("Enter modified marks: "))

# Method to display the modified name and marks


def display_modified_details(self):
print("\nModified Name and Marks:")
print(f"Name: {self.student_name}, Marks: {self.marks}")

# Create an instance of the Student class


x = Student("Abc", 81)

# Display original details


x.get_details()

# Modify the student's details


x.modify_details()

# Display modified details


x.display_modified_details()

Output –
Original Name and Marks:
Name: Abc, Marks: 81
Enter modified name: Tejas
Enter modified marks: 89

Modified Name and Marks:


Name: Tejas, 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

from tkinter import *

# Function to add an item to the Listbox


def add_item():
19
new_item = entry.get() # Get input from the entry box
if new_item: # Check if the input is not empty
listbox.insert(END, new_item)
entry.delete(0, END) # Clear the entry box

# Function to print selected items from the Listbox


def print_items():
selected_items = [listbox.get(i) for i in listbox.curselection()] # Get selected items
print("Selected items:", selected_items)

# Function to delete selected items from the Listbox


def remove_item():
selected_items = listbox.curselection() # Get indices of selected items
for i in selected_items[::-1]: # Reverse the order to avoid index shifting
listbox.delete(i)

# Create the main GUI window


root = Tk()
root.title("Listbox Widget Example")
root.geometry("300x300")

# Entry widget to input new items


entry = Entry(root, width=20)
entry.pack(pady=5)

# Add Button to add items to the Listbox


add_button = Button(root, text="Add", command=add_item)
add_button.pack(pady=5)

# Listbox widget
listbox = Listbox(root, selectmode=MULTIPLE, width=30, height=10)
listbox.pack(pady=5)

# Print Button to print selected items


print_button = Button(root, text="Print", command=print_items)
print_button.pack(pady=5)

# Delete Button to delete selected items


delete_button = Button(root, text="Delete", command=remove_item)
delete_button.pack(pady=5)

# Prepopulate the Listbox with items


items = ["Apple", "Orange", "Grapes", "Banana", "Mango"]
for item in items:
listbox.insert(END, item)

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]

# Input a threshold number


n = int(input("Enter a number to filter the list: "))

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

# Display the results


print(f"Original list: {a}")
print(f"Elements less than {n}: {less_than_n}")
print(f"Elements greater than or equal to {n}: {greater_or_equal_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

from tkinter import *

# Function to clear all input and output fields


def clear_all():
number_field.delete(0, END) # Clear the entry field
listbox.delete(0, END) # Clear the Listbox
22
# Function to generate and display the multiplication table
def multiplication():
try:
# Get the number from the entry field
num = int(number_field.get())
listbox.delete(0, END) # Clear the Listbox before inserting new values

# Generate the multiplication table


for i in range(1, 11):
result = f"{num} x {i} = {num * i}"
listbox.insert(END, result) # Add the result to the Listbox
except ValueError:
listbox.insert(END, "Please enter a valid number") # Error message for invalid input

# 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)

# Number input label and entry field


Label(gui, text="Enter a number:", bg="lightgreen", font=("Arial", 12)).pack(pady=5)
number_field = Entry(gui, font=("Arial", 12), width=20)
number_field.pack(pady=5)

# Buttons for result and clear


Button(gui, text="Show Table", command=multiplication, bg="gray", fg="black", font=("Arial",
12)).pack(pady=10)
Button(gui, text="Clear All", command=clear_all, bg="red", fg="white", font=("Arial",
12)).pack(pady=5)

# Listbox to display the multiplication table


listbox = Listbox(gui, font=("Arial", 12), bg="white", fg="black", width=30, height=12)
listbox.pack(pady=10)

# Run the GUI


gui.mainloop()

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)

from math import pi

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)

# Input the radius of the circle


radius = float(input("Enter the radius of the circle: "))

# Create an object of the Circle class


circle = Circle(radius)

# Display the results


print(f"Area of the circle: {circle.area()}")
print(f"Circumference of the circle: {circle.circumference()}")

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))

# Original tuple with string values


tup1 = (('333', '33'), ('1416', '55'))

# Converting the tuple of string values to a tuple of integer values


# Using nested list comprehensions and tuple conversion
new_tup = tuple(tuple(int(i) for i in inner) for inner in tup1)

# Display the results


25
print("Original tuple values:", tup1)
print("New tuple values:", new_tup)

Output –
Original tuple values: (('333', '33'), ('1416', '55'))
New tuple values: ((333, 33), (1416, 55))

Q.17 Write an anonymous function to find area of square and rectangle.

# Anonymous function to calculate the area of a square


area_square = lambda x: x * x

# Input for square side and calculate the area


side = int(input('Enter the side value of square: '))
print(f"Area of square: {area_square(side)}")

# Anonymous function to calculate the area of a rectangle


area_rectangle = lambda x, y: x * y
26
# Input for rectangle length and width and calculate the area
length = int(input('Enter the length value of rectangle: '))
width = int(input('Enter the width value of rectangle: '))
print(f"Area of rectangle: {area_rectangle(length, width)}")

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?

from tkinter import *


from tkinter import messagebox

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

altersField.insert(0, newstr) # Display altered string

if __name__ == "__main__":
gui = Tk()
gui.configure(background="lightgreen")
gui.title("Alter String")
gui.geometry("300x200")

Stringin = Label(gui, text="Given String", bg="#00ffff")


str1 = Label(gui, text="String", bg="lightgreen")
str1Field = Entry(gui)

result = Button(gui, text="Result", fg="Black", bg="gray", command=occurrences)


alters = Label(gui, text="Altered String", bg="lightgreen")
altersField = Entry(gui)

clearAllEntry = Button(gui, text="Clear All", fg="Black", bg="Red", command=clearAll)


28
# Grid Layout
Stringin.grid(row=0, column=1)
str1.grid(row=1, column=0)
str1Field.grid(row=1, column=1)
alters.grid(row=2, column=0)
altersField.grid(row=2, column=1)
clearAllEntry.grid(row=3, column=0)
result.grid(row=3, column=1)

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

from tkinter import *


from tkinter import messagebox
29
# Function to clear all fields
def clearAll():
numberField.delete(0, END)
binaryField.delete(0, END)
octalField.delete(0, END)
hexadecimalField.delete(0, END)

# Function to check if input is valid


def checkError():
if numberField.get() == "":
messagebox.showerror("Input Error", "Please enter a number.")
clearAll()
return -1
return 0

# Function to calculate binary, octal, and hexadecimal values


def calculateConversion():
value = checkError()
if value == -1:
return
else:
try:
number0 = int(numberField.get()) # Convert input to integer
binary = bin(number0)[2:] # Convert to binary and remove the '0b' prefix
octal = oct(number0)[2:] # Convert to octal and remove the '0o' prefix
hexadecimal = hex(number0)[2:] # Convert to hexadecimal and remove the '0x' prefix

# Display the results in the respective fields


binaryField.insert(0, str(binary))
octalField.insert(0, str(octal))
hexadecimalField.insert(0, str(hexadecimal))
except ValueError:
messagebox.showerror("Input Error", "Invalid number entered. Please enter a valid decimal
number.")
clearAll()

if __name__ == "__main__":
# Set up the GUI window
gui = Tk()
gui.configure(background="lightgreen")
gui.title("Decimal Number Converter")
gui.geometry("400x300")

# Create the GUI components


numberLabel = Label(gui, text="Enter Number", bg="#00ffff")
30
numberField = Entry(gui)

resultLabel = Label(gui, text="Results", bg="#00ffff")

resultButton = Button(gui, text="Convert", fg="Black", bg="gray", command=calculateConversion)

binaryLabel = Label(gui, text="Binary", bg="lightgreen")


binaryField = Entry(gui)

octalLabel = Label(gui, text="Octal", bg="lightgreen")


octalField = Entry(gui)

hexadecimalLabel = Label(gui, text="Hexadecimal", bg="lightgreen")


hexadecimalField = Entry(gui)

clearButton = Button(gui, text="Clear All", fg="Black", bg="Red", command=clearAll)

# Position the components using grid layout


numberLabel.grid(row=0, column=1)
numberField.grid(row=1, column=1)

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)

# Start the GUI loop


gui.mainloop()

Output –

31
Program Index
Sr. Page
Program
No. No.

1 Demonstrate singly and doubly linked list using Python Programming 34

2 STACK implementation using Array with PUSH, POP operations using Python 38

32
Programming
3 Reverse a string using stack using Python Programming 40

4 Check for balanced parentheses by using Stacks using Python Programming 41

5 Implement Stack using Linked List using Python Programming 42

6 Demonstration of Linear Queue using Python 44

7 Demonstration of Circular Queue using Python 46

8 Demonstration of Priority Queue using Python 49

9 Reverse stack using queue 51

10
Practical based on binary search tree implementation with its operations 53

11 Write a program for a linear search using python programming 57

12 Write a program in python for binary search 58

13
Write a program in python for merge sort 59

14 Implement quick sort using python 61

15
Write a program in python for bubble sort 62

16
Write a program of heap sort using python 63

Implementation of conversion of an expression (Infix Prefix Postfix) using


17 64
python programming
18
Write a program of sparse matrix using python programming 66

Write a program of reverse of a string using python programming (Don’t use


19 68
inbuilt function)
Write a program to find out age (year,month,days) in this program read current
20 69
Date and birthdate and find out how old are you?

Q.1 Demonstrate singly and doubly linked list using Python Programming

# Singly Linked List


class Node:
def __init__(self, data):
self.data = data
self.next = None
33
class SinglyLinkedList:
def __init__(self):
self.head = None

def append(self, data):


new_node = Node(data)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node

def display(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")

def delete(self, key):


current = self.head
if current and current.data == key:
self.head = current.next
current = None
return
prev = None
while current and current.data != key:
prev = current
current = current.next
if current is None:
print(f"{key} not found in the list.")
return
prev.next = current.next
current = None

# Demonstrate Singly Linked List


print("Singly Linked List:")
sll = SinglyLinkedList()
sll.append(1)
sll.append(2)
sll.append(3)
sll.display()
sll.delete(2)
34
sll.display()

Output :
Singly Linked List:
1 -> 2 -> 3 -> None
1 -> 3 -> None

# Doubly Linked List


class DoublyNode:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None

35
class DoublyLinkedList:
def __init__(self):
self.head = None

def append(self, data):


new_node = DoublyNode(data)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
new_node.prev = current

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")

def delete(self, key):


current = self.head
while current and current.data != key:
current = current.next
if current is None:
print(f"{key} not found in the list.")
return
if current.prev:
current.prev.next = current.next
if current.next:
current.next.prev = current.prev
if current == self.head: # If the head node is to be deleted
self.head = current.next
current = 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 push(self, item):


"""Add an item to the stack."""
self.stack.append(item)
print(f"Pushed: {item}")
37
def pop(self):
"""Remove and return the top item from the stack."""
if self.is_empty():
print("Stack Underflow! Cannot pop from an empty stack.")
return None
item = self.stack.pop()
print(f"Popped: {item}")
return item

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.

Q.3 Reverse a string using stack using Python Programming

def reverse_string_with_stack(input_string):
# Initialize an empty stack
stack = []

# Push all characters of the string onto the stack


for char in input_string:
stack.append(char)

# Pop characters from the stack and append to the reversed string
reversed_string = ""
39
while stack:
reversed_string += stack.pop()

return reversed_string

# Test the function


original_string = "hello"
reversed_string = reverse_string_with_stack(original_string)

print(f"Original String: {original_string}")


print(f"Reversed String: {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 = []

# Dictionary to match closing and opening brackets


matching_parentheses = {')': '(', '}': '{', ']': '['}

for char in expression:


# If the character is an opening bracket, push it onto the stack
if char in '({[':
stack.append(char)
40
# If the character is a closing bracket
elif char in ')}]':
# Check if the stack is empty or the top of the stack doesn't match
if not stack or stack[-1] != matching_parentheses[char]:
return False
# Pop the matching opening bracket
stack.pop()

# If the stack is empty, all brackets are balanced


return len(stack) == 0

# Test the function


test_expressions = [
"()", # Balanced
"(]", # Not Balanced
"([{}])", # Balanced
"((())", # Not Balanced
"([)]", # Not Balanced
"{[()]}", # Balanced
]

for expr in test_expressions:


print(f"Expression: {expr} -> Balanced: {is_balanced(expr)}")

Output –
Expression: () -> Balanced: True
Expression: (] -> Balanced: False
Expression: ([{}]) -> Balanced: True
Expression: ((()) -> Balanced: False
Expression: ([)] -> Balanced: False
Expression: {[()]} -> Balanced: True

Q.5 Implement Stack using Linked List using Python Programming

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 push(self, data):


41
"""Push an element onto the stack."""
new_node = Node(data)
new_node.next = self.top
self.top = new_node
print(f"Pushed: {data}")

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")

# Demonstrate Stack using Linked List


stack = Stack()
print("Stack Operations:")
stack.push(10)
stack.push(20)
stack.push(30)
stack.display()
42
stack.pop()
stack.display()

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.

Q.6 Demonstration of Linear Queue using Python

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 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 += 1
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 += 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])

# Demonstrate Linear Queue


queue = LinearQueue(5)
print("Queue Operations:")
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
queue.display()

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.

Q.7 Demonstration of Circular Queue using Python

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()

# Demonstrate Circular Queue


queue = CircularQueue(5)
print("Circular Queue Operations:")
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
queue.enqueue(40)
46
queue.display()

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 enqueue(self, item, priority):


"""Add an element to the priority queue with a given priority."""
heapq.heappush(self.queue, (priority, item))
print(f"Enqueued: {item} with priority {priority}")

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)

# Demonstrate Priority Queue


pq = PriorityQueue()
print("Priority Queue Operations:")
pq.enqueue("Task A", 3)
pq.enqueue("Task B", 1)
pq.enqueue("Task C", 2)
pq.display()

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.

Q.9 Reverse stack using queue

from queue import Queue

class Stack:
"""Stack implementation using a list."""
def __init__(self):
self.stack = []

def push(self, item):


"""Push an item onto the stack."""
self.stack.append(item)

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()

# Transfer all elements from the stack to the queue


while not stack.is_empty():
q.put(stack.pop())

# Transfer all elements back from the queue to the stack


while not q.empty():
stack.push(q.get())

# Demonstration
print("Original Stack:")
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.display()

print("\nReversing the Stack...")


reverse_stack(stack)

print("\nReversed Stack:")
stack.display()

Output –
Original Stack:
Stack contents (top to bottom): [4, 3, 2, 1]

Reversing the Stack...

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 insert(self, key):


"""Insert a key into the BST."""
if self.root is None:
self.root = Node(key)
else:
self._insert(self.root, key)

def _insert(self, current, key):


if key < current.key:
if current.left is None:
current.left = Node(key)
52
else:
self._insert(current.left, key)
elif key > current.key:
if current.right is None:
current.right = Node(key)
else:
self._insert(current.right, key)

def search(self, key):


"""Search for a key in the BST."""
return self._search(self.root, key)

def _search(self, current, key):


if current is None:
return False
if current.key == key:
return True
elif key < current.key:
return self._search(current.left, key)
else:
return self._search(current.right, key)

def delete(self, key):


"""Delete a key from the BST."""
self.root = self._delete(self.root, key)

def _delete(self, current, key):


if current is None:
return None
if key < current.key:
current.left = self._delete(current.left, key)
elif key > current.key:
current.right = self._delete(current.right, key)
else:
# Node with one child or no child
if current.left is None:
return current.right
elif current.right is None:
return current.left
# Node with two children
successor = self._min_value_node(current.right)
current.key = successor.key
current.right = self._delete(current.right, successor.key)
return current

def _min_value_node(self, node):


53
"""Get the node with the smallest key in a subtree."""
current = node
while current.left is not None:
current = current.left
return current

def in_order(self):
"""In-order traversal of the BST."""
result = []
self._in_order(self.root, result)
return result

def _in_order(self, current, result):


if current is not None:
self._in_order(current.left, result)
result.append(current.key)
self._in_order(current.right, result)

def pre_order(self):
"""Pre-order traversal of the BST."""
result = []
self._pre_order(self.root, result)
return result

def _pre_order(self, current, result):


if current is not None:
result.append(current.key)
self._pre_order(current.left, result)
self._pre_order(current.right, result)

def post_order(self):
"""Post-order traversal of the BST."""
result = []
self._post_order(self.root, result)
return result

def _post_order(self, current, result):


if current is not None:
self._post_order(current.left, result)
self._post_order(current.right, result)
result.append(current.key)

# Demonstration of BST Operations


bst = BinarySearchTree()

# 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())

print("\nDeleting key 30 (node with one child)")


bst.delete(30)
print("In-order Traversal:", bst.in_order())

print("\nDeleting key 50 (node with two children)")


bst.delete(50)
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]

Searching for key 40: True


Searching for key 100: False

Deleting key 20 (leaf node)


In-order Traversal: [30, 40, 50, 60, 70, 80]

Deleting key 30 (node with one child)


In-order Traversal: [40, 50, 60, 70, 80]
55
Deleting key 50 (node with two children)
In-order Traversal: [40, 60, 70, 80]

Q.11 Write a program for a linear search using python programming

def linear_search(arr, target):


"""Perform linear search on the list to find the target element."""
for i in range(len(arr)):
if arr[i] == target:
return i # Return the index of the found element
return -1 # Return -1 if the element is not found

# Example usage of linear_search


arr = [10, 20, 30, 40, 50, 60]
target = 30

# Perform the linear search


result = linear_search(arr, target)

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

def binary_search(arr, target):


"""Perform binary search on the sorted list to find the target element."""
low = 0
high = len(arr) - 1

while low <= high:


mid = (low + high) // 2 # Find the middle index
if arr[mid] == target:
return mid # Target found, return the index
elif arr[mid] < target:
low = mid + 1 # Target is in the right half
else:
high = mid - 1 # Target is in the left half

return -1 # Return -1 if the target is not found

# Example usage of binary_search


arr = [10, 20, 30, 40, 50, 60, 70, 80, 90]
target = 40

# Perform the binary search


result = binary_search(arr, target)

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.

Q.13 Write a program in python for merge sort

def merge_sort(arr):
"""Sort the array using merge sort algorithm."""
if len(arr) <= 1:
return arr

# Split the array into two halves


mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]

# Recursively sort both halves


left_half = merge_sort(left_half)
right_half = merge_sort(right_half)

# Merge the sorted halves


return merge(left_half, right_half)

def merge(left, right):


"""Merge two sorted arrays."""
result = []
i=j=0

# 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

# Append any remaining elements from left or right


result.extend(left[i:])
result.extend(right[j:])

return result

# Example usage of merge_sort


arr = [38, 27, 43, 3, 9, 82, 10]
print("Original array:", arr)

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]

# Partition the array into two halves


less_than_pivot = [x for x in arr[:-1] if x <= pivot]
greater_than_pivot = [x for x in arr[:-1] if x > pivot]

# Recursively apply quick sort to both halves and concatenate with pivot
return quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot)

# Example usage of quick_sort


arr = [38, 27, 43, 3, 9, 82, 10]
print("Original array:", arr)

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

# Example usage of bubble_sort


arr = [64, 34, 25, 12, 22, 11, 90]
print("Original array:", 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

# Function to heapify a subtree rooted at index i


def heapify(arr, n, i):
largest = i # Initialize largest as root
left = 2 * i + 1 # left child
right = 2 * i + 2 # right child

# Check if left child of root exists and is greater than root


if left < n and arr[left] > arr[largest]:
largest = left

# Check if right child of root exists and is greater than root


if right < n and arr[right] > arr[largest]:
largest = right

# If largest is not root, swap and heapify the affected subtree


if largest != i:
arr[i], arr[largest] = arr[largest], arr[i] # Swap
heapify(arr, n, largest)

# Main function to implement heap sort


def heap_sort(arr):
n = len(arr)

# Build a max heap (rearrange the array)


for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)

# One by one extract elements from the heap


for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # Swap
heapify(arr, i, 0)

61
# Example usage
arr = [12, 11, 13, 5, 6, 7]
print("Original array:", arr)

heap_sort(arr)

print("Sorted array:", 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

# Function to check if a character is an operator


def is_operator(c):
return c in ['+', '-', '*', '/']

# Function to check the precedence of operators


def precedence(op):
if op == '+' or op == '-':
return 1
if op == '*' or op == '/':
return 2
return 0

# Function to perform the operation


def apply_operator(operand1, operand2, operator):
if operator == '+':
return operand1 + operand2
elif operator == '-':
return operand1 - operand2
elif operator == '*':
return operand1 * operand2
elif operator == '/':
return operand1 / operand2

# Function to convert infix expression to postfix


def infix_to_postfix(expression):
stack = []
postfix = []
for char in expression:
if char.isalnum(): # Operand (Variable or Number)
postfix.append(char)
elif char == '(': # Left Parenthesis
stack.append(char)
elif char == ')': # Right Parenthesis
62
while stack and stack[-1] != '(':
postfix.append(stack.pop())
stack.pop() # Pop '('
elif is_operator(char): # Operator
while stack and precedence(stack[-1]) >= precedence(char):
postfix.append(stack.pop())
stack.append(char)

while stack:
postfix.append(stack.pop())

return ''.join(postfix)

# Function to convert infix expression to prefix


def infix_to_prefix(expression):
# Reverse the expression and swap the parentheses
expression = expression[::-1]
expression = expression.replace('(', 'temp').replace(')', '(').replace('temp', ')')

# Convert the reversed expression to postfix


postfix = infix_to_postfix(expression)

# Reverse the postfix expression to get the prefix


return postfix[::-1]

# 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 = {}

# Method to insert an element into the sparse matrix


def insert(self, row, col, value):
if value != 0:
self.matrix[(row, col)] = value

# Method to get an element from the sparse matrix


def get(self, row, col):
return self.matrix.get((row, col), 0)

# Method to display the sparse matrix


def display(self):
print("Sparse Matrix (only non-zero elements):")
for (row, col), value in self.matrix.items():
print(f"Position ({row}, {col}) -> {value}")

# Method to add two sparse matrices


def add(self, other):
if self.rows != other.rows or self.cols != other.cols:
raise ValueError("Matrix dimensions must match for addition.")

result = SparseMatrix(self.rows, self.cols)

# Add elements from the first matrix


for (row, col), value in self.matrix.items():
result.insert(row, col, value)

# Add elements from the second matrix


for (row, col), value in other.matrix.items():
64
current_value = result.get(row, col)
result.insert(row, col, current_value + value)

return result

# Method to multiply two sparse matrices


def multiply(self, other):
if self.cols != other.rows:
raise ValueError("Matrix dimensions must match for multiplication.")

result = SparseMatrix(self.rows, other.cols)

# Multiply the matrices


for (row, col), value in self.matrix.items():
for k in range(other.cols):
if (col, k) in other.matrix:
result_value = value * other.get(col, k)
current_value = result.get(row, k)
result.insert(row, k, current_value + result_value)

return result

# Example usage:

# Create two sparse matrices


A = SparseMatrix(3, 3)
B = SparseMatrix(3, 3)

# Insert non-zero elements into matrix A


A.insert(0, 0, 5)
A.insert(1, 1, 8)
A.insert(2, 2, 3)

# Insert non-zero elements into matrix B


B.insert(0, 2, 7)
B.insert(1, 0, 6)
B.insert(2, 1, 4)

# Display the sparse matrices


print("Matrix A:")
A.display()

print("\nMatrix B:")
B.display()

# Add matrices A and B


65
C = A.add(B)
print("\nMatrix A + B:")
C.display()

# Multiply matrices A and B


D = A.multiply(B)
print("\nMatrix A * B:")
D.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)

print(f"Original String: {input_string}")


print(f"Reversed String: {reversed_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?

from datetime import datetime

# Function to calculate the age in years, months, and days


def calculate_age(birthdate):
# Get the current date
current_date = datetime.now()

# Calculate the difference in years, months, and days


years = current_date.year - birthdate.year
months = current_date.month - birthdate.month
days = current_date.day - birthdate.day

# Adjust if the birthdate hasn't occurred yet this year


if days < 0:
months -= 1
days += (30 if current_date.month == 2 else 31) # Approximate days in a month

if months < 0:
years -= 1
months += 12

return years, months, days

# Input: Current Date and Birthdate


def get_date_input(prompt):
date_input = input(prompt)
return datetime.strptime(date_input, "%Y-%m-%d")

# Main function
def main():
# Get the current date and birthdate from user input
birthdate = get_date_input("Enter your birthdate (YYYY-MM-DD): ")

# Calculate the age


years, months, days = calculate_age(birthdate)

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

You might also like