| class PriorityQueue:
|
| def __init__(self):
|
| self.data = []
|
| def parent(self, j):
|
| return (j - 1) // 2
|
| def left(self, j):
|
| return 2 * j + 1
|
| def right(self, j):
|
| return 2 * j + 2
|
| def swap(self, i, j):
|
| self.data[i], self.data[j] = self.data[j], self.data[i]
|
|
|
| def upheap(self, j):
|
| while j > 0 and self.data[j][0] < self.data[self.parent(j)][0]:
|
| self.swap(j, self.parent(j))
|
| j = self.parent(j)
|
|
|
| def downheap(self, j):
|
| n = len(self.data)
|
| while self.left(j) < n:
|
| small = self.left(j)
|
| r = self.right(j)
|
| if r < n and self.data[r][0] < self.data[small][0]:
|
| small = r
|
| if self.data[j][0] <= self.data[small][0]:
|
| break
|
| self.swap(j, small)
|
| j = small
|
| def add(self, key, value):
|
| self.data.append((key, value))
|
| self.upheap(len(self.data) - 1)
|
| def minimum(self):
|
|
|
| if not self.data:
|
|
|
| return "Priority Queue is Empty"
|
| return self.data[0]
|
| def remove_min(self):
|
| self.swap(0, len(self.data) - 1)
|
| item = self.data.pop()
|
| if self.data:
|
| self.downheap(0)
|
| return item
|
|
|
| pq = PriorityQueue()
|
| while True:
|
| print("\nHeaps Using Priority Queues")
|
| print("Menu")
|
| print("1 - Insertion")
|
| print("2 - Remove the Highest Priority")
|
| print("3 - Display Heap")
|
| print("4 - Exit")
|
| choice = int(input("Enter your choice: "))
|
| if choice == 1:
|
|
|
| while True:
|
| key = int(input("Enter priority key: "))
|
| value = input("Enter value: ")
|
| pq.add(key, value)
|
| print("Element inserted successfully.")
|
| cont = input("Do you want to insert more? (y/n): ").lower()
|
| if cont != 'y':
|
| break
|
| elif choice == 2:
|
| if not pq.data:
|
| print("Priority Queue is Empty")
|
| else:
|
| print("Removed the Highest Priority element:", pq.remove_min())
|
| elif choice == 3:
|
|
|
| if not pq.data:
|
| print("Priority Queue is Empty")
|
|
|
| else:
|
| print("Current Heap:", pq.data)
|
| elif choice == 4:
|
| print("Program Exited")
|
| break
|
| else:
|
| print("Invalid choice. Try again.") |