如何使用Queue.PriorityQueue作为maxheap python

时间:2016-12-19 08:54:02

标签: python python-2.7 python-3.x heap priority-queue

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

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

有人可以判断是否可以将Queue.PriorityQueue用作maxheap

4 个答案:

答案 0 :(得分:0)

默认情况下,PriorityQueue仅支持minheap。

一种实现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())

答案 1 :(得分:0)

基于注释,获取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())

答案 2 :(得分:0)

是的,有可能。

假设您有一个列表:

k = [3,2,6,4,9]

现在,假设您要先打印出max元素(或其他具有最高优先级的元素)。然后,逻辑是通过将优先级乘以-1来反转优先级,然后使用支持最小优先级队列的PriorityQueue类对象使其成为最大优先级队列。

例如:

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]

注意:库在Python3中是queue.PriorityQueue

答案 3 :(得分:0)

反转键的值并使用heapq。例如,将 1000.0 变为 -1000.0,将 5.0 变为 -5.0。

n % 2 != 0