How to Use Queue. Priorityqueue as Maxheap Python

How to Use Queue. Priorityqueue as Maxheap Python

How to use Queue.PriorityQueue as maxheap python?

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.

Can someone tell whether it is possible to use Queue.PriorityQueue as maxheap or not

3

4 Answers

PriorityQueue by default, only support minheaps.

One way to implement max_heaps with it, could be,

# Max Heap
class MaxHeapElement(object):

    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())

Yes, it is possible.

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:

k = [3,2,6,4,9]
q = 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]

NB: Library is queue.PriorityQueue in Python3

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

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())

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.