0% found this document useful (0 votes)
45 views46 pages

Practical File 2024-25

Uploaded by

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

Practical File 2024-25

Uploaded by

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

C O M P U T E R S C I E N C E (083)

Practical File
session 2024-25

S T Te r e s a S c h o o l
Submitted to: Mrs Vinita Sharma
Shakti Khand-II, (HOD Cs)
Indirapuram Ghaziabad- Submitted by: Aneek Chatterjee
201014 (U.P) India
INDEX
1 - 4 STRING

5 - 9 LIST

10 - 12 TUPLE

13 - 16 D I C T I O N A RY

17 - 21 C S V FILE

22 - 27 B I N A RY FILE

28 - 34 TEXT FILE

35 - 38 PYTHON S Q L CONNECTIVITY

39 - 43 S TA C K
STRING

Write a program to check if a given string is a


Question palindrome or not. A palindrome is a word that is
1 the same when read backwards. For example,
“madam” is a palindrome, but “python” is not.

Answer :
s = input("Enter a string: " )

r = s[::-1]

if s == r:
print("The string is a
palindrome.")
else:
print("The string is not a
palindrome.")

Output

Question 2 Write a program to find the longest common


prefix of a list of strings. For example, if the list is
[“flower”, “flow”, “flight”], the output should be
“fl”.
Answer :
def longest_common_prefix(lst):
# If the list is empty, return an
empty stringif not lst:
return " " # If the list has only
one element, return that elementif
len(lst) == 1:
return lst[0]

lst.sort()
prefix = lst[0]
for i in
range(1,
len(lst)):
while not lst[i].startswith(prefix):
prefix = prefix[:-1]
if prefix == "":
break
return prefix
lst = input("Enter a list of strings separated by
commas: ").split(",")

print("The longest common prefix is:",


longest_common_prefix(lst))

OUTPUT

QUESTION 3 Write a program to convert a given string to title


case. Title case means that the first letter of
each word is capitalized, except for articles,
conjunctions, and prepositions.
For example, if the string is “the lord of the
rings”, the output should be “The Lord of the
Rings”.

ANSWER:

def title_case(s):
words = s.split()
new_words =
[]
skip_words = {"the", "of", "and", "or", "in", "a",
"an"}

for word in words:


if word.lower() not in skip_words:
word = word[0].upper() + word[1:]

new_words.append(word
) return "
".join(new_words)

s = input("Enter a string: " )


print("The title case string is:",
title_case(s))

OUTPUT

QUESTION 4 Write a program to generate a random password


of a given length, using lowercase letters,
uppercase letters, digits, and symbols. For
example, if the length is 8, the output could be
“aB3!d@f”.
A N S W ER
: import random
def random_password(length):
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
MNOPQRSTUVWXYZ0123456789!@#$%^&*"
password = " "
for i in range(length):
password += random.choice(chars)

return password
length = int(input("Enter the length of the
password: "))

print("The random password is:",


random_password(length))

OUTPUT
L IS T
QUESTION Consider a list L=[1,2,3,4,5,2,4,2]
1 Write a user defined function SearchReplace()
that would access every element in the list
and replace those divisible by 2 by 0 and an
appropriate message is displayed is every
element is divisible by 2.
ANSWER:
L=[1,2,3,4,5,2,4,2]
n=2
def SearchReplace(L,n):
k=0
for i in range(len(L)):
if L[i]==n:
L[i]=0
else:
k=
1 if
k==0
print("Number not found")
print("The updated list is",
L)
SearchReplace(L,n)

O UTPUT

QUESTION 2 Consider a list L=[1,2,3,4,5,6,7,8,9,10] and that K


is equal to 2 write a python program to
replace the number divisible by 2 by 0 if every
elements
is divisible by 2 an appropriate message should
be displayed

A N S W ER
L=[1,2,3,4,5,6,7,8,9,10]
:
n=2
def SearchReplace(L,n):
k=0
for i in range(len(L)):
if L[i]%n==0:
L[i]=0
else:
k=
1 if
k==0:
print("Number not found")
print("The updated List
is",L)
O UTPUT SearchReplace(L,n)

QUESTION 3 Create a list of n prime numbers, where n is


entered by the user. A prime number is a natural
number that has exactly two factors: 1 and
itself. For example, the first 10 prime numbers
are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29.
A N S W ER - def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1): if
n % i == 0:
return False
return True
def prime_list(n):
prime_list = []
count = 0
num = 2
while count < n:
if is_prime(num):
prime_list.append(num)
count += 1
num += 1
return prime_list
n = int(input("Enter the number of prime
numbers: "))
print("The list of prime numbers is:",
prime_list(n))

O UTPUT

QUESTION 4 Create a list of n even numbers, where n is


entered by the user. An even number is a natural
number that is divisible by 2. For example, the
first 10 even numbers are: 2, 4, 6, 8, 10, 12, 14,
16,
18, 20 .
A N S W ER -
def even_list(n):
even_list =
[] num = 2
for i in range(n):
even_list.append(num)
num += 2
return even_list

n = int(input("Enter the number of even numbers:


"))

print("The list of even numbers is:", even_list(n))

O UTPUT

QUESTION 5 Create a list of n odd numbers, where n is entered


by the user. An odd number is a natural number
that is not divisible by 2. For example, the first 10
odd numbers are: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19.

ANSWER-
def odd_list(n):
odd_list = []
num = 1
for i in range(n):
odd_list.append(num)
num += 2
return odd_list
n = int(input("Enter the number of odd numbers:
"))
print("The list of odd numbers is:", odd_list(n))

O UTPUT
T U PL E

QUESTION Create a tuple of 5 elements and print the second


1 and fourth elements of the tuple.

A N S W ER -
t = (10, 20, 30, 40, 50)
print("The second element is:", t[1])
print("The fourth element is:", t[3])

O UTPUT

QUESTION 2 Swap the values of two tuples using a third tuple.


For example, if the tuples are (1, 2, 3) and (4, 5,
6), the output should be (4, 5, 6) and (1, 2, 3).

A N S W ER -
t1 = (1, 2, 3)
t2 = (4, 5, 6)
print("The original tuples are:")
print("t1 =", t1)
print("t2 =", t2)
t3 = t1
t1 = t2
t2 =
t3
print("The swapped tuples are:")
print("t1 =", t1)
print("t2 =", t2)

O UTPUT

QUESTION 3 Count the number of occurrences of a given


element in a tuple. For example, if the tuple is (1,
2, 3, 1, 4 , 1) and the element is 1, the output
should
be 3.
ANSWER-
t = (1, 2, 3, 1, 4 , 1)
e = int(input("Enter the element to be counted:
"))
c = t.count(e)
print("The element", e, "occurs", c, "times in the
tuple.")

OUTPUT
QUESTION 4 Sort a tuple of strings in alphabetical order. For
example, if the tuple is (“apple”, “banana”,
“cherry”), the output should be (“apple”,
“banana”, “cherry”).

ANSWER-
t = ("apple", "banana", "cherry")
print("The original tuple is:", t) t =
tuple(sorted(t))
print("The sorted tuple is:", t)

O UTPUT

QUESTION 5 Convert a list of numbers into a tuple of numbers.


For example, if the list is [1, 2, 3, 4, 5], the output
should be (1, 2, 3, 4, 5).

A N S W ER -
l = [1, 2, 3, 4, 5]
print("The original list is:", l)
t = tuple(l)
print("The converted tuple
is:", t)

O UTPUT
D I C T I O NA RY
QUESTION Create a dictionary of students and their marks,
1 where the keys are the names of the students and
the values are their marks. Then, print the
dictionary and the average mark of the class.

A N S W ER -
students = {"Alice": 85, "Bob": 90, "Charlie": 75,
"Dav id": 80, "Eve": 95}
print("The dictionary of students and their marks
is:", students)
total = 0
for mark in students.values():
total += mark
average = total / len(students)
print("The average mark of the class is:",
average)

O UTPUT

QUESTION 2 Create a dictionary of words and their meanings,


where the keys are the words and the values are
their meanings. Then, ask the user to enter a word
and print its meaning if it exists in the dictionary,
or print “Word not found” otherwise.
words = {"python": " a high-level programming
A N S W ER -
language", "bing": " a web search engine",
"tuple": "an immutable sequence of values in
Python"}
word = input("Enter a word: " )
if word in words:
print("The meaning of", word, "is:",
words[word])
else:
print("Word not found")

O UTPUT

QUESTION 3 Create a dictionary of products and their prices,


where the keys are the names of the products and
the values are their prices. Then, ask the user to
enter a product name and print its price if it exists
in the dictionary, or print “Product not found”
otherwise.

A N S W ER - products = {"apple": 0.99, "banana": 0.79,


"cherry": 1.29, "orange": 0.89, "pear": 1.09}
product = input("Enter a product name: " )
if product in products:
print("The price of", product, "is:",
products[product])
else:
print("Product not found")
O UTPUT

QUESTION 4 Create a dictionary of countries and their capitals,


where the keys are the names of the countries
and the values are their capitals. Then, ask the
user to enter a country name and print its
capital if it exists in the dictionary, or print
“Country not found” otherwise.

A N S W ER -
countries = {"India": "New Delhi", "China":
"Beijing", "Japan": "Tokyo", "France":
"Paris", "Germany": "Berlin"}
country = input("Enter a country name: " )

if country in countries:
print("The capital of", country, "is:",
countries[country])
else:
print("Country not found")

OUTPUT
QUESTION 5 Create a dictionary of employees and their
salaries, where the keys are the names of the
employees and the values are their salaries. Then,
print the dictionary and the name of the
employee with the highest salary.

A N S W ER -
employees = {"Alice": 5000, "Bob": 6000,
"Charlie": 4000, "Dav id": 7000, "Eve": 8 0 0 0 }
print("The dictionary of employees and their
salaries is:", employees)
max_salary = 0
max_name =
""
for name, salary in employees.items():
if salary > max_salary:
max_salary = salary
max_name = name
print("The name of the employee with the highest
salary is:", max_name)

O UTPUT
CSV FILE
QUESTION Write a program to read a C S V file named
1 “students.csv” that contains the names and marks
of five students in two columns, and print the
name and percentage of each student. Assume
that the total marks are 100. If the file content is:
Alice,85
Bob,90
C harlie,7
5
David,80
Eve,95
A N S W ER -
import csv
f = open("students.csv", "r")
reader = csv.reader(f)
name = row[0]
mark = int(row[1])
percentage = mark / 100 * 100
print(name + ": " + str(percentage) + " % " )

f.close()

O UTPUT
Q U E S T I O N 2 Write a C S V file named “products.csv” that
contains the names and prices of four products in
two columns, and then read the file and print
the total price of all the products. For example,
if the file content is:
Apple,0.99 Banana,0.79
Cherry,1.29
O rang e,0 .8
9

A N S W ER -
import csv
f = open("products.csv", " w " )
writer = csv.writer(f)
writer.writerow(["Apple", 0.99])
writer.writerow(["Banana",
0.79])
writer.writerow(["Cherry", 1.29])
writer.writerow(["Orange", 0.89])
f.close()
f = open("products.csv", "r")
reader = csv.reader(f)
total = 0
for row in reader:
price = float(row[1])
total += price
print("The total price is:", total)
f.close()

O UTPUT
QUESTION 3 Write a program to read a C S V file named
“countries.csv” that contains the names and
capitals of five countries in two columns, and then
ask the user to enter a country name and print
its capital if it exists in the file, or print “Country
not found” otherwise. For example, if the file
content is:
India,New Delhi
China,Beijing
Japan,Tokyo
France,Paris
Germany,Berlin

A N S W ER -
import csv
f = open("countries.csv", "r")
reader = csv.reader(f)
countries = {}
for row in reader:
country = row[0]
capital = row[1]
countries[country] = capital
f.close()
country = input("Enter a country name:
" ) if country in countries:
print("The capital of", country,
"is:", countries[country])
else:
print("Country not found")

O UTPUT
QUESTION 4 Write a program to read a C S V file named
“employees.csv” that contains the names,
departments, and salaries of five employees in
three columns, and then print the name and
department of the employee with the lowest
salary. For example, if the file content is:
Arun,IT,5000
Bimal,HR,6000
Charlie,Finance,4000
Danish,Marketing,7000
Esther,Sales,8000

A N S W ER -
import csv
f = open("employees.csv", "r")
reader = csv.reader(f)
min_salary = float("inf")
min_name = " "
min_dept = " "
for row in reader:
name = row[0]
dept = row[1]
salary = float(row[2])
if salary <
min_salary:
min_salary = salary
min_name = name
min_dept = dept
print("The employee with the lowest salary is:",
min_name)
print("The department of the employee with the
lowest salary is:", min_dept)
f.close()
O UTPUT

QUESTION 5 Write a program to write a C S V file named


“fruits.csv” that contains the names and colors of
four fruits in two columns, and then read the file
and print the name of the fruit that has the
color “red”. For example, if the file content is:
Apple,red
Banana,yellow
Cherry,red
O rang e,orang
A N S W ER - e
import csv
f = open("fruits.csv", " w " )
writer = csv.writer(f)
writer.writerow(["Apple", "red"])
writer.writerow(["Banana", "yellow"])
writer.writerow(["Cherry", "red"])
writer.writerow(["Orange", "orange"])
f.close()
f = open("fruits.csv", "r")
reader = csv.reader(f)
for row in reader:
name = row[0]
color = row[1]
if color ==
"red":
print("The fruit that has the color red is:",
name)
f.close()
O UTPUT
B I NA RY F I L E
QUESTION Write a program to create a binary file named
1 “numbers.dat” that contains the numbers from 1
to 10 in binary format, and then read the file
and print the numbers in decimal format.

ANSWER-
import struct
f = open("numbers.dat", " w b " )
for i in range(1, 11):
data = struct.pack('i', i)
f.write(data)
f.close()

f = open("numbers.dat", "rb")
while True:
data = f.read(4)
if not data:
break
num = struct.unpack('i', data)[0]
print(num)
f.close()

OUTPUT
QUESTION 2 Write a program to read a binary file named
“image.jpg” that contains an image in
JPEG format, and then write the file as
“image_copy.jpg” in the same format.

A N S W ER -
f = open("image.jpg", "rb")
data = f.read()

f.close()

f = open("image_copy.jpg", " w b " )


f.write(data)

f.close()

O UTPUT A copy of the original image.

QUESTION 3 Write a program to read a binary file named


“music.mp3” that contains an audio in MP3
format, and then print the size of the file in bytes.

A N S W ER -
import os
size = os.path.getsize("music.mp3")

print("The size of the file is:", size, "bytes")

O UTPUT
QUESTION 4 Write a program to create a binary file named
“students.dat” that contains the names and marks
of three students in two fields, and then read the
file and print the name and percentage of each
student. Assume that the total marks are 100.

ANSWER-
import pickle
f = open("students.dat", " w b " )
students = [("Alice", 85), ("Bob", 90), ("Charlie", 75)]
pickle.dump(students, f)

f.close()

f = open("students.dat", "rb") students =


pickle.load(f) f.close()
for name, mark in students:
percentage = mark / 100 * 100
print(name + ": " +
str(percentage) + " % " )

O UTPUT

QUESTION 5 Write a program to read a binary file named


“data.dat” that contains a list of numbers in
binary format, and then print the sum and
average of the numbers. For example, if the file
content is:
[1, 2, 3, 4, 5]
ANSWER-
import pickle
f = open("data.dat", "rb")
numbers = pickle.load(f)

f.close()

total = sum(numbers)
average = total / len(numbers)
print("The sum of the numbers is:", total)
print("The average of the numbers is:",
average)

O UTPUT

Q U E S T I O N 6 Create a binary file with name and roll number.

Search for a given roll number and display the

name, if not found display appropriate message.


A N S W ER - import pickle

def writetob():
with open('students.pickle', 'wb') as binary_file:
name = input('Enter Name')
roll_number = int(input('Enter roll number'))
student = [name, roll_number]
pickle.dump(student, binary_file)

def Search(roll_number):
try:
with open('students.pickle', 'rb') as binary_file:
while True:
try:
student = pickle.load(binary_file)
if student[1] == roll_number:
print("Name:", student[0])
return
except EOFError:
print("Roll number not found.")
break
except:
print('An Error occurred')

writetob()
roll_no = 30
Search(roll_no)

O UTPUT

Q U E S T I O N 7 Create a binary file with roll number, name and

marks. Input a roll number and update the marks.

ANSWER-
import pickle

def writetob():
with open('students.pickle', 'ab') as binary_file:
roll_number = int(input('Enter roll number: '))
name = input('Enter Name: ')
marks = int(input('Enter marks: '))
student = {'roll_number': roll_number, 'name':
name, 'marks': marks}
pickle.dump(student, binary_file)

def Search(roll_number, new_marks):


try:
with open('students.pickle', 'rb+') as binary_file:
while True:
try:
student = pickle.load(binary_file)
if student[0] == roll_number:
student[2] = new_marks
binary_file.seek(0)
pickle.dump(student,
binary_file)
print("Marks updated
successfully.")
return
except EOFError:
break
except Exception as e:
print(f"An error occurred: {e}")

writetob()
roll_no = 30
new_marks = 90
Search(roll_no, new_marks)

O UTPUT
T E X T FILE
Q U E S T I O N 1 Write a program to create a text file named
“hello.txt” that contains the word “Hello” in it,
and then read the file and print the word on the
screen.
ANSWER-
f = open("hello.txt", " w " )
f.write("Hello")

f.close()

f = open("hello.txt", "r") word =


f.read() print(word)

f.close()

OUTPUT

QUESTION 2 Write a program to read a text file named


“story.txt” that contains a story in it, and then
print the number of characters, words, and
sentences in the file. For example, if the file
content is:
Once upon a time, there was a king who had three sons. The
king was old and wanted to choose one of his
sons as his successor. He decided to test their
wisdom and courage by giv ing them a task.
He asked each of his sons to bring him the most beautiful
thing they could find in the world.
A N S W ER - f = open("story.txt", "r")
text = f.read()

f.close()

chars = len(text)
words = len(text.split())
sentences = len(text.split("."))
print("The number of characters is:", chars)
print("The number of words is:", words)
print("The number of sentences is:", sentences)

OUTPUT

Q U E S T I O N 3 Write a program to write a text file named


“table.txt” that contains the multiplication table
of a number entered by the user, and then
read the file and print the table on the screen.
For example, if the user enters 5, the file
content should be:
5 x 1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
A N S W ER - n = int(input("Enter a number: " ))
f = open("table.txt", " w " )
for i in range(1, 11):
product = n * i
f.write(str(n) + " x " + str(i) + " = " +
str(product) + " \ n " )

f.close()

f = open("table.txt", "r")
table = f.read()
print(table)

f.close()

OUTPUT

Q U E S T I O N 4 Write a program to read a text file named


“names.txt” that contains the names of five
people in each line, and then print the names in
alphabetical order. For example, if the file
content is:
Alice,Bob,Charlie,David,Eve
Frank,Grace,Henry,Irene,Jack
Karen,Liam,Mia,Noah,Olivia
A N S W ER - f = open("names.txt", "r")
names = []
for line in f:
names.extend(line.strip().split(","))

f.close()

names.sort()
for name in names:
print(name)

O UTPUT

Q U E S T I O N 5 Write a Python program to read a text file named


“data.txt” and print each word in a new line.

A N S W ER -
file = open("data.txt", "r")
line = file.readline()
values = line.split(" ")
for value in values:
print(value)
file.close()

O UTPUT
Q U E S T I O N 6 Read a text file line by line and display each word

separated by a #.
A N S W ER - def process_file():
try:
with open('data.txt', 'r') as file:
for line in file:
words = line.split()
formatted_line = '#'.join(words)
print(formatted_line)
except FileNotFoundError:
print("File not found.")
process_file()

O UTPUT

Q U E S T I O N 7 Read a text file and display the number of

vowels/consonants/uppercase/lowercase

A N S W ER - def count_characters():
characters in the file.
vowels = "aeiouAEIOU"
consonants =
"bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTV
WXYZ"
uppercase_count = 0
lowercase_count = 0
vowel_count = 0
consonant_count = 0
try:
with open('data.txt', 'r') as file:
content = file.read()
for char in content:
if char.isalpha():
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1

if char in vowels:
vowel_count += 1
elif char in consonants:
consonant_count += 1

print(f"Uppercase characters:
{uppercase_count}")
print(f"Lowercase characters:
{lowercase_count}")
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")

except FileNotFoundError:
print("File not found.")

count_characters()

O UTPUT
Q U E S T I O N 6 Read all the lines that contain the character 'a' in a

file and write it to another file.


A N S W ER - def remove_lines_with_a():
try:
with open('data.txt', 'r') as input_file, open('write.txt',
'w') as output_file:
for line in input_file:
if 'a' not in line:
output_file.write(line)
except FileNotFoundError:
print(f"File not found.")

remove_lines_with_a()

O UTPUT
PYTHON SQL
C O N N E C T IV IT Y
Q U E S T I O N 1 Write a Python program to connect to a
SQLdatabase named “school.db” using the
sqlite3 module and print the names of the
tables in the database.
ANSWER-
import mysql.connector as m
con = m.connect("school.db") cursor =
con.cursor()
cursor.execute("SELECT name F R O M
sqlite_master W H E R E type='table'")
result = cursor.fetchall()
print("The names of the tables in the database are:")
for row in result:
print(row[0])
cursor.close()
con.close()

OUTPUT

Q U E S T I O N 2 Write a Python program to create a table named


“courses” in the SQL database “school.db”
with the following columns: id (integer, primary
key), name (text), and teacher_id (integer,
foreign key referencing teachers.id).
A N S W ER -
import mysql.connector as m
con = m.connect("school.db")
cursor = con.cursor()
cursor.execute("CREATE TABLE courses (id
INTEGER P R I M A RY KEY, name TEXT, teacher_id
INTEGER, FO REI G N K E Y (teacher_id)
R E F E R E N C E S teachers (id))")

con.commit()

cursor.close(
) con.close()

N o output on the screen, but the table “courses”


O UTPUT
will be created in the database.

Q U E S T I O N 3 Write a Python program to insert three records


into the table “courses” in the SQL database
“school.db” using the executemany() method of
the cursor object. The records are: (1, ‘Math’, 101),
(2, ‘English’, 102), and (3, ‘Science’, 103).
A N S W ER -
import mysql.connector as m
con = m.connect("school.db")
cursor = con.cursor()
sql = "IN SERT INTO courses (id, name,
teacher_id) VA L U E S (?, ?, ? ) "
values = [
(1, 'Math', 101),
(2, 'English', 102),
(3, 'Science', 103)
]
cursor.executemany(sql, values)
con.commit()
print(f"{cursor.rowcount} rows
inserted")

cursor.close(
) con.close()

OUTPUT

QUESTION 4 Write a Python program to fetch and display all


the records from the table “courses” in the SQL
database “school.db” using the fetchall() method
of the cursor object.
A N S W ER -
import mysql.connector as m
con = m .connect("school.db") cursor =
con.cursor() cursor.execute("SELECT *
F R O M courses") result = cursor.fetchall()
print("id\tname\teacher_id")
for row in result: print(f"{row[0]}\
t{row[1]}\t{row[2]}")
cursor.close(
) con.close()

O UTPUT
QUESTION 5 Write a Python program to update the name of
the course with id 2 to ‘Literature’ in the table
“courses” in the SQL database “school.db”
using the execute() method of the cursor object.

A N S W ER - import mysql.connector as m
con = m.connect("school.db")
cursor = conn.cursor()
sql = " U P D AT E courses SET name
= ? W H E R E id =
?
values = ('Literature', 2)
cursor.execute(sql, values)
con.commit() print(f"{cursor.rowcount}
row updated")
cursor.close(
) con.close()

OUTPUT
STAC K
Q U E S T I O N 1 Write a Python program to check if a given string
is a palindrome using a stack. A palindrome is
a word that is the same when read forward or
backward. For example, “madam” and “racecar”
are palindromes.
A N S W ER -
def is_palindrome(string):
stack = []
for char in string:
stack.append(char)
for i in range(len(string)):
if string[i] !=
stack.pop(): return False
return True
print(is_palindrome("madam")) # True
print(is_palindrome("racecar")) #
True print(is_palindrome("python")) #
False
O UTPUT

QUESTION 2 Write a Python p r o g ra m to implement a stack


using a list. The stack should have the following
methods: push(item), pop(), peek(),
is_empty(), and size().
A N S W ER -
class Stack:
def init
(self): self.items
= []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
s = Stack()
s.push(1)
s.push(2)
s.push(3)
print(s.peek()) # 3
print(s.pop()) # 3
print(s.size()) # 2
print(s.is_empty()) # False

OUTPUT

QUESTION 3 Write a Python program to reverse a string using


a stack.
A N S W ER -
def reverse_string(string):
stack = []
for char in string:
stack.append(char)
reversed_string = " "
while not len(stack) == 0:
reversed_string += stack.pop()
return reversed_string

print(reverse_string("hello")) # olleh
print(reverse_string("stack")) #
kcats

OUTPUT

QUESTION 4 Write a Python program to check if a given


expression has balanced parentheses using a
stack. Balanced parentheses mean that every
opening parenthesis has a matching closing
parenthesis and vice versa. For example, “(a+b)
(c-d)" and “((a+b)+(c-d))” are balanced, but "
(a+b)(c-d))” and “((a+b)+(c-d)” are not.
A N S W ER -
def is_balanced(expression):
stack = []
for char in expression:
if char == "(":
stack.append(char)
elif char == ")":
if len(stack) == 0:
return False
if stack.pop() != "(":
return False
if len(stack) != 0:
return False
return True
print(is_balanced("(a+b)*(c-d)")) # True
O UTPUT
print(is_balanced("((a+b)+(c-d))")) # True
print(is_balanced("(a+b)*(c-d))")) #
False print(is_balanced("((a+b)+(c-d)"))
# False

QUESTION 5 Write a Python program to print the elements of a


stack in reverse order using another stack. You
can use the following steps to print the stack in
reverse order:
Create an empty stack called reverse_stack.
While the original stack is not empty, do
the following:
Pop an element from the original stack and
push it to the reverse_stack.
While the reverse_stack is not empty, do the
following:
Pop an element from the reverse_stack and
print it.
ANSWER-
def print_reverse(stack):
reverse_stack = []
while not len(stack) == 0:
reverse_stack.append(stack.pop())
while not len(reverse_stack) == 0:
print(reverse_stack.pop())
stack = [1, 2, 3, 4, 5]
print("The original stack is:")
print(stack)
print("The reversed stack is:")
print_reverse(stack)
O UTPUT
THANKYOU

You might also like