5

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

Prashant Bhanarkar
  • 930
  • 3
  • 14
  • 32

5 Answers5

6

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())
Kushagra Verma
  • 361
  • 4
  • 7
2

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

srth12
  • 873
  • 9
  • 16
1

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())
Vaibhav Desai
  • 2,334
  • 2
  • 25
  • 29
0

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
Pay C.
  • 1,048
  • 1
  • 13
  • 20
0

@Kusharga has an elegant answer above. To adhere to the (priority, value) structure for an element in a priority queue, the wrapper class can be modified as below:

class MaxHeapElement(object):

   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}"
pakpe
  • 5,391
  • 2
  • 8
  • 23