如何使用 Queue.PriorityQueue 作为 maxheap python

Pra*_*kar 6 python heap priority-queue python-2.7 python-3.x

如何使用Queue.PriorityQueue作为maxheap python?

Queue.PriorityQueue 的默认实现是 minheap,文档中也没有提及是否可以用于 maxheap。

有人可以告诉是否可以使用 Queue.PriorityQueue 作为 maxheap 吗

小智 6

PriorityQueue默认只支持minheaps。

用它实现 max_heaps 的一种方法可能是,

# 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())
Run Code Online (Sandbox Code Playgroud)