Untitled Document
Untitled Document
import pickle
def add_record():
try:
with open("Test.dat", "ab") as file:
pickle.dump({'roll': int(input("Enter Roll
Number: ")), 'name': input("Enter Name: "), 'marks':
float(input("Enter Marks: "))}, file)
print("Record added successfully.")
except Exception as e:
print("Error:", e)
def average_marks():
try:
with open("Test.dat", "rb") as file:
records = [pickle.load(file)['marks'] for _ in
range(len(file))]
print("Average Marks:", sum(records) /
len(records) if records else "No records found.")
except FileNotFoundError:
print("No records found.")
except Exception as e:
print("Error:", e)
def display_all():
try:
with open("Test.dat", "rb") as file:
for record in iter(lambda: pickle.load(file),
None):
print("Roll:", record['roll'], "Name:",
record['name'], "Marks:", record['marks'])
except FileNotFoundError:
print("No records found.")
except Exception as e:
print("Error:", e)
def main():
while True:
print("\nMenu:\na. ADD # (Add a record)\nb. Average
Marks\nc. Display All\nq. Quit")
choice = input("Enter your choice: ").lower()
if choice == 'a':
add_record()
elif choice == 'b':
average_marks()
elif choice == 'c':
display_all()
elif choice == 'q':
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
ANSWER Q2-
class Stack:
def __init__(self):
self.items = []
def pop(self):
if not self.is_empty():
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
def peek(self):
if not self.is_empty():
return self.items[-1]
def main():
stack = Stack()
while True:
try:
num = int(input("Enter a number (enter 0 to
stop): "))
if num == 0:
break
if num % 2 != 0:
stack.push(num)
except ValueError:
print("Please enter a valid integer.")
if stack.is_empty():
print("No odd numbers entered.")
else:
print("Odd numbers in the stack:")
largest_odd = float('-inf')
while not stack.is_empty():
num = stack.pop()
print(num)
if num > largest_odd:
largest_odd = num
print("Largest odd number in the stack:",
largest_odd)
if __name__ == "__main__":
main()
ANSWER Q3-
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
def peek(self):
if not self.is_empty():
return self.items[-1]
def display(self):
if self.is_empty():
print("Stack is empty.")
else:
print("Stack contents:")
for item in reversed(self.items):
print(item)
def main():
stack = Stack()
while True:
print("\nMenu:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Quit")
if choice == '1':
item = input("Enter item to push onto the stack:
")
stack.push(item)
print(item, "pushed onto the stack.")
elif choice == '2':
item = stack.pop()
if item is not None:
print("Popped item:", item)
else:
print("Stack is empty.")
elif choice == '3':
item = stack.peek()
if item is not None:
print("Top item on the stack:", item)
else:
print("Stack is empty.")
elif choice == '4':
stack.display()
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
ANSWER Q4-
class StackNode:
def __init__(self, book_number, book_name):
self.book_number = book_number
self.book_name = book_name
self.next = None
class Stack:
def __init__(self):
self.top = None
def display(self):
if not self.top:
print("Stack is empty.")
else:
print("Book Details in the Stack:")
current = self.top
while current:
print("Book Number:", current.book_number,
"Book Name:", current.book_name)
current = current.next
def main():
stack = Stack()
while True:
print("\nMenu:")
print("1. Push Book Details")
print("2. Display Book Details")
print("3. Quit")
if choice == '1':
book_number = input("Enter Book Number: ")
book_name = input("Enter Book Name: ")
stack.push(book_number, book_name)
print("Book details pushed onto the stack.")
elif choice == '2':
stack.display()
elif choice == '3':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
ANSWER Q5-
def write_to_file():
try:
with open("text_file.txt", "a") as file:
data = input("Enter text to write into the file:
")
file.write(data + "\n")
print("Data written to file successfully.")
except Exception as e:
print("Error:", e)
def read_from_file():
try:
with open("text_file.txt", "r") as file:
print("Data read from file:")
print(file.read())
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Error:", e)
def count_words_starting_with_a():
try:
with open("text_file.txt", "r") as file:
words = file.read().split()
count = sum(1 for word in words if
word.lower().startswith('a'))
print("Total number of words starting with 'A' or
'a':", count)
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Error:", e)
def main():
while True:
print("\nMenu:")
print("a. Write into file")
print("b. Reading all data from file")
print("c. Count and display total no Words present in
file starting with 'A' or 'a'")
print("q. Quit")
if choice == 'a':
write_to_file()
elif choice == 'b':
read_from_file()
elif choice == 'c':
count_words_starting_with_a()
elif choice == 'q':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
ANSWER Q6-
def write_to_file():
try:
with open("Study.txt", "w") as file:
lines = [
"Me and my friend and his father went to
market.",
"My favorite color is blue.",
"I like to read books and listen to music."
]
for line in lines:
file.write(line + "\n")
print("Data written to 'Study.txt' successfully.")
except Exception as e:
print("Error:", e)
def count_occurrences():
try:
with open("Study.txt", "r") as file:
text = file.read()
count_and = text.lower().count("and")
count_my = text.lower().count("my")
print("Occurrences of 'and':", count_and)
print("Occurrences of 'my':", count_my)
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Error:", e)
def main():
write_to_file()
count_occurrences()
if __name__ == "__main__":
main()
ANSWER Q7-
class Stack:
def __init__(self):
self.items = []
def display(self):
if not self.items:
print("Stack is empty.")
else:
print("Employee Details in the Stack:")
for employee in self.items:
print("Employee Code:", employee[0],
"Employee Name:", employee[1])
def main():
employee_stack = Stack()
# Initial employees
employees = [
(101, "Kamal"),
(102, "Rajesh"),
(103, "Kush")
]
if __name__ == "__main__":
main()
ANSWER Q8-
class Employee:
def __init__(self, code, name, salary):
self.code = code
self.name = name
self.salary = salary
def add_employee(stack):
code = input("Enter Employee Code: ")
name = input("Enter Employee Name: ")
salary = float(input("Enter Salary: "))
employee = Employee(code, name, salary)
stack.append(employee)
print("Employee record added successfully.")
def delete_employee(stack):
if not stack:
print("Stack is empty. No records to delete.")
return
print("Employee record deleted:")
employee = stack.pop()
print("Employee Code:", employee.code)
print("Employee Name:", employee.name)
print("Salary:", employee.salary)
def display_employees(stack):
if not stack:
print("Stack is empty. No records to display.")
return
print("Employee Records:")
for employee in reversed(stack):
print("Employee Code:", employee.code)
print("Employee Name:", employee.name)
print("Salary:", employee.salary)
print()
def main():
stack = []
while True:
print("\nMenu:")
print("1. Add Employee Record")
print("2. Delete Employee Record")
print("3. Display Employee Records")
print("4. Quit")
if choice == '1':
add_employee(stack)
elif choice == '2':
delete_employee(stack)
elif choice == '3':
display_employees(stack)
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
ANSWER Q9-
class Player:
def __init__(self, code, score, rank):
self.code = code
self.score = score
self.rank = rank
def add_player(stack):
code = input("Enter Player Code: ")
score = int(input("Enter Player Score: "))
rank = int(input("Enter Player Rank: "))
player = Player(code, score, rank)
stack.append(player)
print("Player record added successfully.")
def delete_player(stack):
if not stack:
print("Stack is empty. No records to delete.")
return
print("Player record deleted:")
player = stack.pop()
print("Player Code:", player.code)
print("Player Score:", player.score)
print("Player Rank:", player.rank)
def display_players(stack):
if not stack:
print("Stack is empty. No records to display.")
return
print("Player Records:")
for player in reversed(stack):
print("Player Code:", player.code)
print("Player Score:", player.score)
print("Player Rank:", player.rank)
print()
def main():
stack = []
while True:
print("\nMenu:")
print("1. Add Player Record")
print("2. Delete Player Record")
print("3. Display Player Records")
print("4. Quit")
if __name__ == "__main__":
main()
ANSWER Q10-
def add_employee(stack):
emp_number = input("Enter Employee Number: ")
emp_name = input("Enter Employee Name: ")
stack.append((emp_number, emp_name))
print("Employee added successfully.")
def delete_employee(stack):
if not stack:
print("Stack is empty. No records to delete.")
else:
emp_number, emp_name = stack.pop()
print("Employee deleted successfully:")
print("Employee Number:", emp_number)
print("Employee Name:", emp_name)
def display_employees(stack):
if not stack:
print("Stack is empty. No records to display.")
else:
print("Employee Records:")
for emp_number, emp_name in reversed(stack):
print("Employee Number:", emp_number)
print("Employee Name:", emp_name)
def main():
employee_stack = []
while True:
print("\nMenu:")
print("1. Add Employee")
print("2. Delete Employee")
print("3. Display Employees")
print("4. Quit")
if choice == '1':
add_employee(employee_stack)
elif choice == '2':
delete_employee(employee_stack)
elif choice == '3':
display_employees(employee_stack)
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
ANSWER Q11-
def count_spaces(text):
return text.count(' ')
def count_digits(text):
count = 0
for char in text:
if char.isdigit():
count += 1
return count
def count_words(text):
words = text.split()
return len(words)
def count_lines(text):
lines = text.split('\n')
return len(lines)
def read_text_file(filename):
try:
with open(filename, 'r') as file:
return file.read()
except FileNotFoundError:
print("File not found.")
return ""
except Exception as e:
print("Error:", e)
return ""
def main():
filename = "TOY.txt"
text = read_text_file(filename)
while True:
print("\nMenu:")
print("1. Count Spaces")
print("2. Count Digits")
print("3. Count Words")
print("4. Count Lines")
print("5. Quit")
if __name__ == "__main__":
main()
ANSWER Q12-
def write_to_file():
try:
with open("text_file.txt", "a") as file:
data = input("Enter text to write into the file:
")
file.write(data + "\n")
print("Data written to file successfully.")
except Exception as e:
print("Error:", e)
def read_from_file():
try:
with open("text_file.txt", "r") as file:
print("Data read from file:")
print(file.read())
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Error:", e)
def count_lines():
try:
with open("text_file.txt", "r") as file:
line_count = sum(1 for line in file)
print("Total lines present in file:", line_count)
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Error:", e)
def main():
while True:
print("\nMenu:")
print("a. Write into file")
print("b. Reading all data from file")
print("c. Count and show total lines present in
file")
print("q. Quit")
if choice == 'a':
write_to_file()
elif choice == 'b':
read_from_file()
elif choice == 'c':
count_lines()
elif choice == 'q':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
ANSWER Q13-
def find_frequency(lst):
frequency_dict = {}
duplicates = []
for item in lst:
if item in frequency_dict:
frequency_dict[item] += 1
if frequency_dict[item] == 2:
duplicates.append(item)
else:
frequency_dict[item] = 1
def main():
original_list = [1, 2, 3, 5, 6, 3, 2, 1, 4]
unique_elements, duplicate_elements =
find_frequency(original_list)
if __name__ == "__main__":
main()
ANSWER Q14-
def write_to_file():
try:
with open("Study.txt", "w") as file:
lines = [
"This is a sample line of text.",
"These are some words in a sentence.",
"My friend and his father went to the
market."
]
for line in lines:
file.write(line + "\n")
print("Data written to 'Study.txt' successfully.")
except Exception as e:
print("Error:", e)
def count_occurrences():
try:
with open("Study.txt", "r") as file:
text = file.read()
count_this = text.lower().count("this")
count_these = text.lower().count("these")
print("Occurrences of 'this':", count_this)
print("Occurrences of 'these':", count_these)
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Error:", e)
def main():
write_to_file()
count_occurrences()
if __name__ == "__main__":
main()
ANSWER Q15-
def write_to_file():
try:
with open("text_file.txt", "a") as file:
data = input("Enter text to write into the file:
")
file.write(data + "\n")
print("Data written to file successfully.")
except Exception as e:
print("Error:", e)
def read_from_file():
try:
with open("text_file.txt", "r") as file:
print("Data read from file:")
print(file.read())
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Error:", e)
def count_words():
try:
with open("text_file.txt", "r") as file:
text = file.read()
words = text.split()
print("Total words present in file:", len(words))
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Error:", e)
def main():
while True:
print("\nMenu:")
print("a. Write into file")
print("b. Reading all data from file")
print("c. Count and show total words present in
file")
print("q. Quit")
if choice == 'a':
write_to_file()
elif choice == 'b':
read_from_file()
elif choice == 'c':
count_words()
elif choice == 'q':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()