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.
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())
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With