如何使用Queue.PriorityQueue作为maxheap python

问题描述 投票:0回答:5

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

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

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

python python-2.7 python-3.x heap priority-queue
5个回答
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())

2
投票

是的,这是可能的。

假设您有一个清单:

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


1
投票
根据评论,获取 maxHeap 最简单的方法是插入元素的负数。

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

0
投票
反转键的值并使用heapq。例如,将 1000.0 变为 -1000.0,将 5.0 变为 -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
    

0
投票
@Kusharga 上面有一个优雅的答案。要遵守优先级队列中元素的(优先级,值)结构,可以按如下方式修改包装类:

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}"
    
© www.soinside.com 2019 - 2024. All rights reserved.