Comp Pract File
Comp Pract File
Input:
Enter a number: 121
Output:
121 is a palindrome.
Input:
Enter a number: 123
Output:
123 is not a palindrome.
1
Question 2:
Write a menu driven program in python to check whether a number is an
Armstrong number or prime number or neon number or Krishnamurthy number.
Solution Code:
import math
while True:
print("\nMenu:")
print("1. Check Armstrong")
print("2. Check Prime")
print("3. Check Neon")
print("4. Check Krishnamurthy")
print("5. Exit")
choice = int(input("Enter your choice: "))
if choice == 5:
break
number = int(input("Enter a number: "))
if choice == 1:
order = len(str(number))
sum_digits = 0
temp = number
while temp > 0:
digit = temp % 10
sum_digits += digit ** order
temp //= 10
print(f"{number} is Armstrong: {sum_digits == number}")
elif choice == 2:
if number <= 1:
2
print(f"{number} is Prime: False")
else:
for i in range(2, int(math.sqrt(number)) + 1):
if number % i == 0:
print(f"{number} is Prime: False")
break
else:
print(f"{number} is Prime: True")
elif choice == 3:
square = number * number
sum_digits = 0
while square > 0:
sum_digits += square % 10
square //= 10
print(f"{number} is Neon: {sum_digits == number}")
elif choice == 4:
sum_factorials = 0
temp = number
while temp > 0:
digit = temp % 10
factorial = 1
for i in range(1, digit + 1):
factorial *= i
sum_factorials += factorial
temp //= 10
print(f"{number} is Krishnamurthy: {sum_factorials == number}")
else:
print("Invalid choice!")
3
Input:
Enter your choice: 1
Enter a number: 153
Enter your choice: 2
Enter a number: 7
Enter your choice: 3
Enter a number: 9
Enter your choice: 4
Enter a number: 145
Enter your choice: 5
Output:
Menu:
1. Check Armstrong
2. Check Prime
3. Check Neon
4. Check Krishnamurthy
5. Exit
153 is Armstrong: True
Menu:
1. Check Armstrong
2. Check Prime
3. Check Neon
4. Check Krishnamurthy
5. Exit
7 is Prime: True
Menu:
4
1. Check Armstrong
2. Check Prime
3. Check Neon
4. Check Krishnamurthy
5. Exit
9 is Neon: True
Menu:
1. Check Armstrong
2. Check Prime
3. Check Neon
4. Check Krishnamurthy
5. Exit
145 is Krishnamurthy: True
Menu:
1. Check Armstrong
2. Check Prime
3. Check Neon
4. Check Krishnamurthy
5. Exit
5
Question 3:
Write a program in python to find sum and average of list in Python without using
built-in functions.
Solution Code:
Input:
Enter numbers separated by space: 10 20 30 40
Output:
Sum: 100
Average: 25.0
Input:
Enter numbers separated by space: 5 15
Output:
Sum: 20
Average: 10.0
6
Question 4:
Write a program to remove all duplicates from a dictionary.
Solution Code:
Input:
Enter number of key-value pairs: 5
Enter key: a
Enter value: 1
Enter key: b
Enter value: 2
Enter key: c
Enter value: 1
Enter key: d
7
Enter value: 3
Enter key: e
Enter value: 2
Output:
Original Dictionary: {'a': 1, 'b': 2, 'c': 1, 'd': 3, 'e': 2}
After removing duplicates: {'a': 1, 'b': 2, 'd': 3}
8
Question 5:
Write a program to define a function to accept two integers m and n respectively as
argument and display prime numbers between them.
Solution Code:
import math
m = int(input("Enter starting number m: "))
n = int(input("Enter ending number n: "))
primes = []
for num in range(m, n + 1):
if num <= 1:
continue
is_prime = True
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)
print("Prime numbers between", m, "and", n, ":", primes)
Input:
Enter starting number m: 10
Enter ending number n: 20
Output:
Prime numbers between 10 and 20: [11, 13, 17, 19]
9
Question 6:
Write a program to show basic operations Push, Pop and show element in stack.
Solution Code:
stack = []
n = int(input("Enter number of elements to push: "))
for i in range(n):
element = int(input(f"Enter element {i+1} to push: "))
stack.append(element)
print(f"Pushed {element} to stack.")
print("Stack elements (top to bottom):", stack[::-1])
if stack:
element = stack.pop()
print(f"Popped {element} from stack.")
print("Stack elements (top to bottom):", stack[::-1])
Input:
Enter number of elements to push: 3
Enter element 1 to push: 10
Enter element 2 to push: 20
Enter element 3 to push: 30
Output:
Pushed 10 to stack.
Pushed 20 to stack.
Pushed 30 to stack.
Stack elements (top to bottom): [30, 20, 10]
Popped 20 from stack.
Stack elements (top to bottom): [10]
10
Question 7:
Write a program to compute interest based on different arguments given in the
function.
Solution Code:
Input:
Enter principal amount: 1000
Enter rate of interest: 5
Enter time (years): 2
Output:
Compound interest: 110.25
Simple interest (default): 100.0
11
Question 8:
Write a program to find largest element in a list using a function. Pass list object as
argument.
Solution Code:
Input:
Enter numbers separated by space: 5 12 3 18 9
Output:
Largest element: 18
12
Question 9:
Write a program to count all vowels in a string using a function.
Solution Code:
Input:
Enter a string: Hello World
Output:
Number of vowels: 3
13
Question 10:
Write a program for a random number generator that generates a random number
from 1 to 6 (Simulates a dice)
Hint : Use random module
Solution Code:
import random
n = int(input("Enter number of dice rolls: "))
for i in range(n):
roll = random.randint(1, 6)
print(f"Roll {i+1}: {roll}")
Input:
Enter number of dice rolls: 3
Output:
Roll 1: 4
Roll 2: 2
Roll 3: 6
14
Question 11:
Read a text file line by line and display its words separated by “# ".
Solution Code:
Input:
(File content: "Hello World\nPython Programming")
(No user input required after file creation.)
Output:
Hello##World
Python##Programming
15
Question 12:
Read a text file and display the number of vowels, consonants / uppercase /
lowercase characters in a file.
Solution Code:
Input:
16
(File content: "Hello World\nPYTHON")
(No user input required after file creation.)
Output:
Vowels: 3
Consonants: 8
Uppercase: 6
Lowercase: 5
17
Question 13:
Remove all the lines that contains a character "a" in a file and write it to another
file.
Solution Code:
Input:
(File content: "apple\nbanana\ncat\ndog")
(No user input required after file creation.)
Output:
dog
18
Question 14:
Create a Binary file with name and roll no. Search for a given roll no. and display
the name, if not found display appropriate message.
Solution Code:
import pickle
data = []
n = int(input("Enter number of students: "))
for i in range(n):
name = input(f"Enter name for student {i+1}: ")
roll = int(input(f"Enter roll no. for student {i+1}: "))
data.append((name, roll))
with open("students.dat", "wb") as file:
pickle.dump(data, file)
search_roll = int(input("Enter roll no. to search: "))
found = False
with open("students.dat", "rb") as file:
records = pickle.load(file)
for name, roll in records:
if roll == search_roll:
print(f"Name: {name}")
found = True
break
if not found:
print("Roll no. not found!")
Input:
Enter number of students: 2
19
Enter name for student 1: Alice
Enter roll no. for student 1: 101
Enter name for student 2: Bob
Enter roll no. for student 2: 102
Enter roll no. to search: 101
Output:
Alice
Input:
Enter number of students: 2
Enter name for student 1: Alice
Enter roll no. for student 1: 101
Enter name for student 2: Bob
Enter roll no. for student 2: 102
Enter roll no. to search: 103
Output:
Roll no. not found!
20
Question 15:
Write a menu driven program in Python to create a binary file with roll no, name,
marks, percentage. Input a roll no. and update the record.
Solution Code:
import pickle
while True:
print("\nMenu:")
print("1. Create/Add Record")
print("2. Update Record")
print("3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
data = []
with open("students.dat", "ab") as file:
n = int(input("Enter number of students: "))
for i in range(n):
roll = int(input(f"Enter roll no. for student {i+1}: "))
name = input(f"Enter name for student {i+1}: ")
marks = float(input(f"Enter marks for student {i+1}: "))
percentage = float(input(f"Enter percentage for student {i+1}: "))
record = (roll, name, marks, percentage)
pickle.dump(record, file)
print("Records added successfully.")
elif choice == 2:
search_roll = int(input("Enter roll no. to update: "))
temp_data = []
found = False
21
with open("students.dat", "rb") as file:
try:
while True:
record = pickle.load(file)
if record[0] == search_roll:
found = True
print(f"Found: {record}")
new_marks = float(input("Enter new marks: "))
new_percentage = float(input("Enter new percentage: "))
record = (record[0], record[1], new_marks, new_percentage)
temp_data.append(record)
except EOFError:
pass
if found:
with open("students.dat", "wb") as file:
for record in temp_data:
pickle.dump(record, file)
print("Record updated successfully.")
else:
print("Roll no. not found!")
elif choice == 3:
break
else:
print("Invalid choice!")
Input:
Enter your choice: 1
Enter number of students: 2
22
Enter roll no. for student 1: 101
Enter name for student 1: Alice
Enter marks for student 1: 85.5
Enter percentage for student 1: 85.5
Enter roll no. for student 2: 102
Enter name for student 2: Bob
Enter marks for student 2: 90.0
Enter percentage for student 2: 90.0
Enter your choice: 2
Enter roll no. to update: 101
Found: (101, 'Alice', 85.5, 85.5)
Enter new marks: 88.0
Enter new percentage: 88.0
Enter your choice: 3
Output:
Menu:
1. Create/Add Record
2. Update Record
3. Exit
Records added successfully.
Menu:
1. Create/Add Record
2. Update Record
3. Exit
Record updated successfully.
Menu:
1. Create/Add Record
23
2. Update Record
3. Exit
Input:
Enter your choice: 2
Enter roll no. to update: 103
Output:
Menu:
1. Create/Add Record
2. Update Record
3. Exit
Roll no. not found!
24
Question 16:
Write a program to replace a word from a text file "India.txt".
Solution Code:
Input:
(File content: "India is great\nVisit India")
(No user input required after file creation.)
Output:
Word replaced successfully.
25
Question 17:
Write a program to generate a CSV file named “Happiness.csv”. Each record of CSV
contains these data.
(String) Name of country:
(Integer) Population of country:
(Integer) No. people participated in survey
(Integer) No. of people who are happy: -
Write user defined function to do:-
(i) Insert record into CSV file
(ii) Display
(iii) Update
(iv) Delete
Solution Code:
import csv
def insert_record():
country = input("Enter country name: ")
population = input("Enter population: ")
participants = int(input("Enter number of people participated: "))
happy = int(input("Enter number of people who are happy: "))
with open("happiness.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow([country, population, participants, happy])
print("Record inserted successfully.")
def display_records():
try:
26
with open("happiness.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
except FileNotFoundError:
print("No records found!")
def update_record():
search_country = input("Enter country name to update: ")
temp_data = []
found = False
with open("happiness.csv", "r") as file:
reader = csv.reader(file)
temp_data = list(reader)
for i in range(len(temp_data)):
if temp_data[i][0] == search_country:
found = True
population = input("Enter new population: ")
participants = int(input("Enter new number of people participated: "))
happy = int(input("Enter new number of people who are happy: "))
temp_data[i] = [search_country, population, participants, happy]
break
if found:
with open("happiness.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(temp_data)
print("Record updated successfully.")
else:
27
print("Country not found!")
def delete_record():
search_country = input("Enter country name to delete: ")
temp_data = []
found = False
with open("happiness.csv", "r") as file:
reader = csv.reader(file)
temp_data = list(reader)
with open("happiness.csv", "w", newline="") as file:
writer = csv.writer(file)
for row in temp_data:
if row[0] != search_country:
writer.writerow(row)
else:
found = True
if found:
print("Record deleted successfully.")
else:
print("Country not found!")
while True:
print("\nMenu:")
print("1. Insert Record")
print("2. Display Records")
print("3. Update Record")
print("4. Delete Record")
print("5. Exit")
28
choice = int(input("Enter your choice: "))
if choice == 1:
insert_record()
elif choice == 2:
display_records()
elif choice == 3:
update_record()
elif choice == 4:
delete_record()
elif choice == 5:
break
else:
print("Invalid choice!")
Input:
Enter your choice: 1
Enter country name: India
Enter population: 1400M
Enter number of people participated: 1000
Enter number of people who are happy: 700
Enter your choice: 2
Enter your choice: 1
Enter country name: USA
Enter population: 330M
Enter number of people participated: 800
Enter number of people who are happy: 500
Enter your choice: 2
Enter your choice: 5
29
Output:
Menu:
1. Insert Record
2. Display Records
3. Update Record
4. Delete Record
5. Exit
Record inserted successfully.
Menu:
1. Insert Record
2. Display Records
3. Update Record
4. Delete Record
5. Exit
['India', '1400M', '1000', '700']
Menu:
1. Insert Record
2. Display Records
3. Update Record
4. Delete Record
5. Exit
Record inserted successfully.
Menu:
1. Insert Record
2. Display Records
3. Update Record
4. Delete Record
30
5. Exit
['India', '1400M', '1000', '700']
['USA', '330M', '800', '500']
Menu:
1. Insert Record
2. Display Records
3. Update Record
4. Delete Record
5. Exit
Input (Update):
Enter your choice: 3
Enter country name to update: India
Enter new population: 1390M
Enter new number of people participated: 1100
Enter new number of people who are happy: 750
Enter your choice: 2
Enter your choice: 5
Output:
Menu:
1. Insert Record
2. Display Records
3. Update Record
4. Delete Record
5. Exit
Record updated successfully.
Menu:
31
1. Insert Record
2. Display Records
3. Update Record
4. Delete Record
5. Exit
['India', '1390M', '1100', '750']
['USA', '330M', '800', '500']
Menu:
1. Insert Record
2. Display Records
3. Update Record
4. Delete Record
5. Exit
Input (Delete):
Enter your choice: 4
Enter country name to delete: USA
Enter your choice: 2
Enter your choice: 5
Output:
Menu:
1. Insert Record
2. Display Records
3. Update Record
4. Delete Record
5. Exit
Record deleted successfully.
32
Menu:
1. Insert Record
2. Display Records
3. Update Record
4. Delete Record
5. Exit
['India', '1390M', '1100', '750']
Menu:
1. Insert Record
2. Display Records
3. Update Record
4. Delete Record
5. Exit
Output:
Menu:
1. Insert Record
2. Display Records
3. Update Record
4. Delete Record
5. Exit
Country not found!
33
Question 18:
Create a CSV file by entering user id and password, read and search password for
given user id.
Solution Code:
import csv
while True:
print("\nMenu:")
print("1. Add User")
print("2. Search Password")
print("3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
user_id = input("Enter user id: ")
password = input("Enter password: ")
with open("users.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow([user_id, password])
print("User added successfully.")
elif choice == 2:
search_id = input("Enter user id to search: ")
found = False
with open("users.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
if row[0] == search_id:
print(f"Password for {search_id}: {row[1]}")
found = True
34
break
if not found:
print("User id not found!")
elif choice == 3:
break
else:
print("Invalid choice!")
Output:
Menu:
1. Add User
2. Search Password
3. Exit
User added successfully.
Menu:
1. Add User
2. Search Password
35
3. Exit
User added successfully.
Menu:
1. Add User
2. Search Password
3. Exit
Password for user1: pass123
Menu:
1. Add User
2. Search Password
3. Exit
Output:
Menu:
1. Add User
2. Search Password
3. Exit
User id not found!
36
Question 19:
Write a program to create a binary file "Candidates.dat" which stores the following
information:
Structure of Data field:
Type: Integer, Field: Candidate Id
Type: String, Field: Name
Type: String, Field: Category
Type: Float, Field: Experience
(i) Write a function append() to write data into the binary file.
(u) Write a function display() to display data from the binary file for all candidates
whose experience is more than 10.
Solution Code:
import pickle
def write_data():
candidate_id = int(input("Enter candidate ID: "))
name = input("Enter candidate name: ")
experience = float(input("Enter experience: "))
record = (candidate_id, name, experience)
with open("Candidates.dat", "ab") as file:
pickle.dump(record, file)
print("Data written successfully.")
def display():
found = False
with open("Candidates.dat", "rb") as file:
try:
37
while True:
record = pickle.load(file)
if record[2] > 10:
print(f"ID: {record[0]}, Name: {record[1]}, Experience: {record[2]}")
found = True
except EOFError:
pass
if not found:
print("No candidates with experience more than 10 found!")
while True:
print("\nMenu:")
print("1. Write Data")
print("2. Display Candidates (Experience > 10)")
print("3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
write_data()
elif choice == 2:
display()
elif choice == 3:
break
else:
print("Invalid choice!")
38
Enter candidate name: Alice
Enter experience: 12.5
Enter your choice: 1
Enter candidate ID: 102
Enter candidate name: Bob
Enter experience: 8.0
Enter your choice: 1
Enter candidate ID: 103
Enter candidate name: Charlie
Enter experience: 15.0
Enter your choice: 2
Enter your choice: 3
Output:
Menu:
1. Write Data
2. Display Candidates (Experience > 10)
3. Exit
Data written successfully.
Menu:
1. Write Data
2. Display Candidates (Experience > 10)
3. Exit
Data written successfully.
Menu:
1. Write Data
2. Display Candidates (Experience > 10)
3. Exit
39
Data written successfully.
Menu:
1. Write Data
2. Display Candidates (Experience > 10)
3. Exit
ID: 101, Name: Alice, Experience: 12.5
ID: 103, Name: Charlie, Experience: 15.0
Menu:
1. Write Data
2. Display Candidates (Experience > 10)
3. Exit
Output:
Menu:
1. Write Data
2. Display Candidates (Experience > 10)
3. Exit
No candidates with experience more than 10 found!
40
Question 20:
Write a menu driven program to store and manipulate data in a binary file to
insert, update, delete and display records. Data has following structure. Data
represents Patient Information Dictionary as:
{‘P_ID’: 101, 'P_Name’: 'Shiv', ‘Charges’: 25000 }
File name: patient.dat
Menu:
Add Patient
Display
Search
Update
Delete
Exit
Solution Code:
import pickle
while True:
print("\nMenu:")
print("1. Add Patient")
print("2. Display")
print("3. Search")
print("4. Update")
print("5. Delete")
print("6. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
p_id = int(input("Enter Patient ID: "))
p_name = input("Enter Patient Name: ")
41
charges = float(input("Enter Charges: "))
record = {'P_ID': p_id, 'P_Name': p_name, 'Charges': charges}
with open("patient.dat", "ab") as file:
pickle.dump(record, file)
print("Patient added successfully.")
elif choice == 2:
with open("patient.dat", "rb") as file:
try:
while True:
record = pickle.load(file)
print(record)
except EOFError:
pass
elif choice == 3:
search_id = int(input("Enter Patient ID to search: "))
found = False
with open("patient.dat", "rb") as file:
try:
while True:
record = pickle.load(file)
if record['P_ID'] == search_id:
print(f"Found: {record}")
found = True
break
except EOFError:
pass
if not found:
print("Patient ID not found!")
42
elif choice == 4:
update_id = int(input("Enter Patient ID to update: "))
temp_data = []
found = False
with open("patient.dat", "rb") as file:
try:
while True:
record = pickle.load(file)
temp_data.append(record)
except EOFError:
pass
for i in range(len(temp_data)):
if temp_data[i]['P_ID'] == update_id:
found = True
new_name = input("Enter new Patient Name: ")
new_charges = float(input("Enter new Charges: "))
temp_data[i] = {'P_ID': update_id, 'P_Name': new_name, 'Charges':
new_charges}
break
if found:
with open("patient.dat", "wb") as file:
for record in temp_data:
pickle.dump(record, file)
print("Patient updated successfully.")
else:
print("Patient ID not found!")
elif choice == 5:
delete_id = int(input("Enter Patient ID to delete: "))
43
temp_data = []
found = False
with open("patient.dat", "rb") as file:
try:
while True:
record = pickle.load(file)
temp_data.append(record)
except EOFError:
pass
with open("patient.dat", "wb") as file:
for record in temp_data:
if record['P_ID'] != delete_id:
pickle.dump(record, file)
else:
found = True
if found:
print("Patient deleted successfully.")
else:
print("Patient ID not found!")
elif choice == 6:
break
else:
print("Invalid choice!")
44
Enter Charges: 2500
Enter your choice: 1
Enter Patient ID: 102
Enter Patient Name: Ravi
Enter Charges: 3000
Enter your choice: 2
Enter your choice: 6
Output:
Menu:
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
6. Exit
Patient added successfully.
Menu:
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
6. Exit
Patient added successfully.
Menu:
1. Add Patient
2. Display
45
3. Search
4. Update
5. Delete
6. Exit
{'P_ID': 101, 'P_Name': 'Shiv', 'Charges': 2500.0}
{'P_ID': 102, 'P_Name': 'Ravi', 'Charges': 3000.0}
Menu:
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
6. Exit
Input (Search):
Enter your choice: 3
Enter Patient ID to search: 101
Enter your choice: 3
Enter Patient ID to search: 103
Enter your choice: 6
Output:
Menu:
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
46
6. Exit
Found: {'P_ID': 101, 'P_Name': 'Shiv', 'Charges': 2500.0}
Menu:
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
6. Exit
Patient ID not found!
Menu:
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
6. Exit
Input (Update):
Enter your choice: 4
Enter Patient ID to update: 101
Enter new Patient Name: Shiva
Enter new Charges: 2600
Enter your choice: 2
Enter your choice: 6
Output:
Menu:
47
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
6. Exit
Patient updated successfully.
Menu:
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
6. Exit
{'P_ID': 101, 'P_Name': 'Shiva', 'Charges': 2600.0}
{'P_ID': 102, 'P_Name': 'Ravi', 'Charges': 3000.0}
Menu:
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
6. Exit
Input (Delete):
Enter your choice: 5
Enter Patient ID to delete: 102
Enter your choice: 2
48
Enter your choice: 6
Output:
Menu:
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
6. Exit
Patient deleted successfully.
Menu:
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
6. Exit
{'P_ID': 101, 'P_Name': 'Shiva', 'Charges': 2600.0}
Menu:
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
6. Exit
49
Enter your choice: 3
Enter Patient ID to search: 103
Output:
Menu:
1. Add Patient
2. Display
3. Search
4. Update
5. Delete
6. Exit
Patient ID not found!
50
Question 21:
Write a menu-driven program for stack operations → Push and Pop.
Solution Code:
stack = []
while True:
print("\nMenu:")
print("1. Push")
print("2. Pop")
print("3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
element = int(input("Enter element to push: "))
stack.append(element)
print(f"Pushed {element} to stack.")
elif choice == 2:
if not stack:
print("Stack is empty!")
else:
element = stack.pop()
print(f"Popped {element} from stack.")
elif choice == 3:
break
else:
print("Invalid choice!")
51
Enter element to push: 10
Enter your choice: 1
Enter element to push: 20
Enter your choice: 2
Enter your choice: 2
Enter your choice: 3
Output:
Menu:
1. Push
2. Pop
3. Exit
Pushed 10 to stack.
Menu:
1. Push
2. Pop
3. Exit
Pushed 20 to stack.
Menu:
1. Push
2. Pop
3. Exit
Popped 20 from stack.
Menu:
1. Push
2. Pop
3. Exit
Popped 10 from stack.
52
Menu:
1. Push
2. Pop
3. Exit
Output:
Menu:
1. Push
2. Pop
3. Exit
Stack is empty!
Menu:
1. Push
2. Pop
3. Exit
53
Question 22:
Write a program to push an item into a stack where a dictionary contains the items
as follows:
Sto = { "Shirt": 700, "T-shirt": 750, "Jeans": 1150, "Trouser": 400 }
(a) Write a function to push an element into the stack for those items whose price
is > 850. Also display count of the elements pushed into stack.
(b) Write a function to pop element or remove element and display the stack.
Solution Code:
def push_element():
count = 0
for item, price in Sto.items():
if price > 850:
stack.append(item)
count += 1
print(f"Elements pushed into stack: {stack}")
print(f"Count of elements pushed: {count}")
def pop_element():
if not stack:
print("Stack is empty!")
else:
element = stack.pop()
print(f"Popped element: {element}")
print(f"Updated stack: {stack}")
54
while True:
print("\nMenu:")
print("1. Push Elements")
print("2. Pop Element")
print("3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
push_element()
elif choice == 2:
pop_element()
elif choice == 3:
break
else:
print("Invalid choice!")
Output:
Menu:
1. Push Elements
2. Pop Element
3. Exit
Elements pushed into stack: ['Jeans']
55
Count of elements pushed: 1
Menu:
1. Push Elements
2. Pop Element
3. Exit
Popped element: Jeans
Updated stack: []
Menu:
1. Push Elements
2. Pop Element
3. Exit
Stack is empty!
Menu:
1. Push Elements
2. Pop Element
3. Exit
Output:
Menu:
1. Push Elements
2. Pop Element
56
3. Exit
Elements pushed into stack: ['Jeans']
Count of elements pushed: 1
Menu:
1. Push Elements
2. Pop Element
3. Exit
Popped element: Jeans
Updated stack: []
Menu:
1. Push Elements
2. Pop Element
3. Exit
Elements pushed into stack: ['Jeans']
Count of elements pushed: 1
Menu:
1. Push Elements
2. Pop Element
3. Exit
Popped element: Jeans
Updated stack: []
Menu:
1. Push Elements
2. Pop Element
3. Exit
57