Python_Q14_Q17
Python_Q14_Q17
if ch==1:
item = int(input("Enter item to push: "))
s.push(item)
elif ch==2:
s.pop()
elif ch==3:
s.display()
elif ch==4:
s.size()
elif ch==5:
s.peek()
elif ch==6:
if s.is_empty():
print("Stack is empty")
else:
print("Stack is not empty")
elif ch==7:
print("Exiting The Program")
break
else:
print("Invalid choice... \n Enter etween 1 - 7")
Q15. To create Queue class and implement all its methods.
class Queue:
def __init__(self):
# Initialize an empty list to act as the queue
self.queue = []
q = Queue()
while True:
print("\n=== Queue Operations Menu ===")
print("1. Enqueue")
print("2. Dequeue")
print("3. Peek")
print("4. Check if Empty")
print("5. Size of Queue")
print("6. Display Queue")
print("7. Exit")
if choice == '1':
item = int(input("Enter the item to enqueue: "))
q.enqueue(item)
elif choice == '2':
q.dequeue()
elif choice == '3':
q.peek()
elif choice == '4':
if q.is_empty():
print("Queue is empty.")
else:
print("Queue is not empty.")
elif choice == '5':
q.size()
elif choice == '6':
q.display()
elif choice == '7':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number between 1 and 7.")
Q16. To implement Linear and Binary search on lists:
# Function for Linear Search
def linear_search(lst, target):
for index, value in enumerate(lst):
if value == target:
return index
return -1
low = 0
high = len(lst) - 1
return -1
# Main program
lst = []
n = int(input("Enter list len: "))
for i in range(n):
a = int(input("Enter ele: "))
lst.append(a)
Q17. To sort a list using Insertion sort, Bubble sort and Selection sort:
while True:
print("\n\n=== Sorting Algorithms Menu ===")
print("1. Insertion Sort")
print("2. Bubble Sort")
print("3. Selection Sort")
print("4. Exit")
if ch == '1':
print("Original list = ",lst)
sorted_lst = insertion_sort(lst.copy())
print("List after Insertion Sort: ",sorted_lst)
elif ch == '2':
print("Original list = ",lst)
sorted_lst = bubble_sort(lst.copy())
print("List after Bubble Sort: ",sorted_lst)
elif ch == '3':
print("Original list = ",lst)
sorted_lst = selection_sort(lst.copy())
print("List after Selection Sort: ",sorted_lst)
elif ch == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number between 1 and 4.")