如何使用Queue.PriorityQueue作为maxheap python?
Queue.PriorityQueue 的默认实现是 minheap,文档中也没有提及是否可以用于 maxheap。
有人可以告诉是否可以使用 Queue.PriorityQueue 作为 maxheap
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())
是的,这是可能的。
假设您有一个清单:
k = [3,2,6,4,9]
现在,假设您想首先打印出最大元素(或具有最大优先级的任何其他元素)。然后逻辑是通过乘以
-1
来反转优先级,然后使用支持最小优先级队列的PriorityQueue
类对象使其成为最大优先级队列。
例如:
import queue
k = [3,2,6,4,9]
q = queue.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]
注意:Python3 中的包是
queue.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())
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
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}"