Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use queue.PriorityQueue as maxheap

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.

like image 215
Prashant Bhanarkar Avatar asked Jul 22 '26 15:07

Prashant Bhanarkar


2 Answers

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())
like image 67
Kushagra Verma Avatar answered Jul 25 '26 05:07

Kushagra Verma


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())
like image 40
Vaibhav Desai Avatar answered Jul 25 '26 05:07

Vaibhav Desai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!