0% found this document useful (0 votes)
2 views

Python_Q14_Q17

The document contains implementations of data structures and algorithms in Python, including a Stack and Queue class with their respective methods for basic operations. It also features functions for Linear and Binary search, as well as sorting algorithms like Insertion sort, Bubble sort, and Selection sort, all presented with interactive menus for user input. Each section provides a clear structure for creating and manipulating these data structures and algorithms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python_Q14_Q17

The document contains implementations of data structures and algorithms in Python, including a Stack and Queue class with their respective methods for basic operations. It also features functions for Linear and Binary search, as well as sorting algorithms like Insertion sort, Bubble sort, and Selection sort, all presented with interactive menus for user input. Each section provides a clear structure for creating and manipulating these data structures and algorithms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Python (Q14 to Q17)

Q14. To create Stack class and implement all its methods.


class Stack:
def __init__(self):
self.stack = []

# Push an item onto the stack


def push(self, item):
self.stack.append(item)
print("Pushed ",item," onto the stack")

# Pop an item from the stack


def pop(self):
if not self.is_empty():
item = self.stack.pop()
print("Popped ",item," from the stack")
return item
else:
print("Stack is empty. Nothing to pop.")
return None

# Peek at the top item of the stack without removing it


def peek(self):
if not self.is_empty():
print("Top item is ",self.stack[-1])
return self.stack[-1]
else:
print("Stack is empty. Nothing to peek.")
return None

# Check if the stack is empty


def is_empty(self):
return len(self.stack) == 0

# Get the size of the stack


def size(self):
print("Stack size: ",len(self.stack))
return len(self.stack)
# Display the contents of the stack
def display(self):
if not self.is_empty():
print("Stack contents: ",self.stack)
else:
print("Stack is empty.")
s = Stack()
ch = 0
while True:
print("\n\n\n =======MENU FOR STACK=======")
print("1. Push element")
print("2. Pop element")
print("3. Display stack")
print("4. Size of Stack")
print("5. Peek")
print("6. Is empty")
print("7. Exit")
ch = int(input("Enter your choice: "))

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 = []

# Enqueue an item into the queue


def enqueue(self, item):
self.queue.append(item)
print("Enqueued ",item," into the queue")

# Dequeue an item from the queue


def dequeue(self):
if not self.is_empty():
item = self.queue.pop(0)
print("Dequeued ",item," from the queue")
return item
else:
print("Queue is empty. Nothing to dequeue.")
return None

# Peek at the front item of the queue without removing it


def peek(self):
if not self.is_empty():
print("Front item is ",self.queue[0])
return self.queue[0]
else:
print("Queue is empty. Nothing to peek.")
return None

# Check if the queue is empty


def is_empty(self):
return len(self.queue) == 0

# Get the size of the queue


def size(self):
print("Queue size: ",len(self.queue))
return len(self.queue)

# Display the contents of the queue


def display(self):
if not self.is_empty():
print("Queue contents: ",self.queue)
else:
print("Queue is empty.")

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

choice = input("Enter your choice (1-7): ")

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

# Function for Binary Search


def binary_search(lst, target):
lst.sort()
print("Sorted list for binary search: ",lst)

low = 0
high = len(lst) - 1

while low <= high:


mid = (low + high)//2
if lst[mid] == target:
return mid
elif lst[mid] < target:
low = mid + 1
else:
high = mid - 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)

# Input target value to search


target = int(input("Enter the number to search for: "))

# Perform Linear Search


linear_result = linear_search(lst, target)
if linear_result != -1:
print("Linear Search: ",target," found at index ",linear_result)
else:
print("Linear Search: ",target," not found in the list")
# Perform Binary Search
binary_result = binary_search(lst, target)
if binary_result != -1:
print("Binary Search: ",target," found at index ",binary_result)
else:
print("Binary Search: ",target," not found in the list")

Q17. To sort a list using Insertion sort, Bubble sort and Selection sort:

# Function for Insertion Sort


def insertion_sort(lst):
for i in range(1, len(lst)):
key = lst[i]
j=i-1
while j >= 0 and key < lst[j]:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = key
return lst

# Function for Bubble Sort


def bubble_sort(lst):
n = len(lst)
for i in range(n):
for j in range(0, n - i - 1):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j] # Swap
return lst

# Function for Selection Sort


def selection_sort(lst):
n = len(lst)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if lst[j] < lst[min_idx]:
min_idx = j
lst[i], lst[min_idx] = lst[min_idx], lst[i] # Swap
return lst
# Menu-driven program to select a sorting algorithm
lst = []
n = int(input("Enter len of list: "))
for i in range(n):
a = int(input("Enter ele: "))
lst.append(a)

while True:
print("\n\n=== Sorting Algorithms Menu ===")
print("1. Insertion Sort")
print("2. Bubble Sort")
print("3. Selection Sort")
print("4. Exit")

ch = input("Enter your choice (1-4): ")

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

You might also like