How to use queue.PriorityQueue as maxheap

7.7k views Asked by At

How to use queue.PriorityQueue as maxheap?

The default implementation of queue.PriorityQueue is minheap, in the documentation also there is no mention whether this can be used or not for maxheap.

5

There are 5 answers

0
Pay C. On

Invert the value of the keys and use heapq. For example, turn 1000.0 into -1000.0 and 5.0 into -5.0.

from heapq import heappop, heappush, heapify

heap = []
heapify(heap)

heappush(heap, -1 * 1000)
heappush(heap, -1 * 5)
-heappop(heap) # return 1000
-heappop(heap) # return 5
0
Kushagra Verma On

PriorityQueue by default only support minheaps.

One way to implement max_heaps with it, could be,

from queue import PriorityQueue

# Max Heap
class MaxHeapElement:
    def __init__(self, x):
        self.x = x

    def __lt__(self, other):
        return self.x > other.x

    def __str__(self):
        return str(self.x)


max_heap = PriorityQueue()

max_heap.put(MaxHeapElement(10))
max_heap.put(MaxHeapElement(20))
max_heap.put(MaxHeapElement(15))
max_heap.put(MaxHeapElement(12))
max_heap.put(MaxHeapElement(27))

while not max_heap.empty():
    print(max_heap.get())
0
pakpe On

To adhere to the (priority, value) structure for an element in a priority queue, the wrapper class can be modified as below:

class MaxHeapElement:    
   def __init__(self, priority, value):
       self.priority = priority
       self.value = value

   def __lt__(self, other):
       return self.priority > other.priority

   def __str__(self):
       return f"{self.priority}, {self.value}"
0
srth12 On

Let's say you have a list:

k = [3, 2, 6, 4, 9]

Now, let's say you want to print out the max element first (or any other element with the maximum priority).

Then the logic is to reverse the priority by multiplying it with -1, then use the PriorityQueue class object which supports the min priority queue for making it a max priority queue.

For example:

import queue

k = [3, 2, 6, 4, 9]
q = queue.PriorityQueue()
for idx in range(len(k)):
    # We are putting a tuple to queue - (priority, value)
    q.put((-1 * k[idx], idx))

# To print the max priority element, just call the get()
# get() will return tuple, so you need to extract the 2nd element
print(q.get()[1]
0
Vaibhav Desai On

Based on the comments, the simplest way to get maxHeap is to insert negative of the element.

from queue import PriorityQueue

max_heap = PriorityQueue()

max_heap.put(MaxHeapElement(-10))
max_heap.put(MaxHeapElement(-20))
max_heap.put(MaxHeapElement(-15))
max_heap.put(MaxHeapElement(-12))
max_heap.put(MaxHeapElement(-27))

while not max_heap.empty():
    print(-1*max_heap.get())