File size: 2,544 Bytes
69b3ab8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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] 
    # Heapify Up  
    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) 
    #Heapify Down  
    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 
# Main Program  
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: 
        # Insert loop 
        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.")