简体   繁体   English

不考虑 PriorityQueue 中元素优先级的更新

[英]Update of element's priority in PriorityQueue is not taken into account

from queue import PriorityQueue

pq = PriorityQueue()
x = [20,0]
y = [20,0]
pq.put(x)
pq.put(y)
y[1] = -1
print(x,y) 
while not pq.empty():
    print(pq.get())

The output of the above program is:上述程序的output为:

[20,0]
[20,-1]

Where as the output should be in ascending order:其中 output 应按升序排列:

[20,-1]
[20,0] 

By mutating the pair after it has been put in the queue, you bypass the priority queue's logic.通过在将其放入队列后对其进行变异,您可以绕过优先级队列的逻辑。 It is not notified about the update you made.它不会通知您所做的更新。

If you really have to modify the priority of an element that is already in the queue, then first invalidate it, and add a new element to it that is intended as replacement:如果您确实必须修改已在队列中的元素的优先级,则首先使其无效,然后向其添加一个新元素以作为替换:

from queue import PriorityQueue

inf = float("inf")
pq = PriorityQueue()
x = [20,0]
y = [20,0]
pq.put(x)
pq.put(y)

# create a copy that has the desired modification
newy = [y[0], -1]
pq.put(newy)
# invalidate the element that was already in the queue
y[0] = -inf 
y[1] = -inf

while not pq.empty():
    val = pq.get()
    # ignore invalidated entries
    if val[0] != -inf:
        print(val)

Another approach would be to use heapq instead of queue.PriorityQueue , mutate the element and then call heapify to restore the heap property.另一种方法是使用heapq而不是queue.PriorityQueue ,改变元素,然后调用heapify来恢复堆属性。

from heapq import heapify, heappush, heappop

heap = []
x = [20,0]
y = [20,0]
heappush(heap, x)
heappush(heap, y)

# mutate...
y[1] = -1
# ...and heapify
heapify(heap)

while heap:
    print(heappop(heap))

This looks simpler, but be aware that heapify has a linear time complexity: it visits all elements of the heap.这看起来更简单,但请注意heapify具有线性时间复杂度:它访问堆的所有元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM