Madhan-Alagarsamy commited on
Commit
69b3ab8
·
verified ·
1 Parent(s): 2d5a722

Upload 5.py

Browse files
Files changed (1) hide show
  1. 5.py +80 -0
5.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class PriorityQueue:
2
+ def __init__(self):
3
+ self.data = []
4
+ def parent(self, j):
5
+ return (j - 1) // 2
6
+ def left(self, j):
7
+ return 2 * j + 1
8
+ def right(self, j):
9
+ return 2 * j + 2
10
+ def swap(self, i, j):
11
+ self.data[i], self.data[j] = self.data[j], self.data[i]
12
+ # Heapify Up
13
+ def upheap(self, j):
14
+ while j > 0 and self.data[j][0] < self.data[self.parent(j)][0]:
15
+ self.swap(j, self.parent(j))
16
+ j = self.parent(j)
17
+ #Heapify Down
18
+ def downheap(self, j):
19
+ n = len(self.data)
20
+ while self.left(j) < n:
21
+ small = self.left(j)
22
+ r = self.right(j)
23
+ if r < n and self.data[r][0] < self.data[small][0]:
24
+ small = r
25
+ if self.data[j][0] <= self.data[small][0]:
26
+ break
27
+ self.swap(j, small)
28
+ j = small
29
+ def add(self, key, value):
30
+ self.data.append((key, value))
31
+ self.upheap(len(self.data) - 1)
32
+ def minimum(self):
33
+
34
+ if not self.data:
35
+
36
+ return "Priority Queue is Empty"
37
+ return self.data[0]
38
+ def remove_min(self):
39
+ self.swap(0, len(self.data) - 1)
40
+ item = self.data.pop()
41
+ if self.data:
42
+ self.downheap(0)
43
+ return item
44
+ # Main Program
45
+ pq = PriorityQueue()
46
+ while True:
47
+ print("\nHeaps Using Priority Queues")
48
+ print("Menu")
49
+ print("1 - Insertion")
50
+ print("2 - Remove the Highest Priority")
51
+ print("3 - Display Heap")
52
+ print("4 - Exit")
53
+ choice = int(input("Enter your choice: "))
54
+ if choice == 1:
55
+ # Insert loop
56
+ while True:
57
+ key = int(input("Enter priority key: "))
58
+ value = input("Enter value: ")
59
+ pq.add(key, value)
60
+ print("Element inserted successfully.")
61
+ cont = input("Do you want to insert more? (y/n): ").lower()
62
+ if cont != 'y':
63
+ break
64
+ elif choice == 2:
65
+ if not pq.data:
66
+ print("Priority Queue is Empty")
67
+ else:
68
+ print("Removed the Highest Priority element:", pq.remove_min())
69
+ elif choice == 3:
70
+
71
+ if not pq.data:
72
+ print("Priority Queue is Empty")
73
+
74
+ else:
75
+ print("Current Heap:", pq.data)
76
+ elif choice == 4:
77
+ print("Program Exited")
78
+ break
79
+ else:
80
+ print("Invalid choice. Try again.")