Python堆优先级队列sift_up()

Python堆优先级队列sift_up(),python,queue,heap,priority-queue,Python,Queue,Heap,Priority Queue,我对Python还是比较陌生,但是堆优先级队列有问题。以下是我的init()、str()、add()和我的sift_up()方法: 现在,当我将项目添加到队列中时,它们进入状态良好。我把这个放进终端: pq = PriorityQueue() pq.add(1) pq.add(2) pq.add(45) pq.add(4) pq.add(41) pq.add(5) pq.__str__() 我得到的是“[1,2,5,4,41,45]”。因此,它看起来只是在某种程度上筛选了_up(),并没有完

我对Python还是比较陌生,但是堆优先级队列有问题。以下是我的init()、str()、add()和我的sift_up()方法:

现在,当我将项目添加到队列中时,它们进入状态良好。我把这个放进终端:

pq = PriorityQueue()
pq.add(1)
pq.add(2)
pq.add(45)
pq.add(4)
pq.add(41)
pq.add(5)

pq.__str__()
我得到的是“[1,2,5,4,41,45]”。因此,它看起来只是在某种程度上筛选了_up(),并没有完全重新排序堆

编辑:每当我在队列中添加“1”时,它似乎都会出错。在本例中,我让它在每次添加后返回:

>>> pq.add(5)
[5]
>>> pq.add(53)
[5, 53]
>>> pq.add(531)
[5, 53, 531]
>>> pq.add(5131)
[5, 53, 531, 5131]
>>> pq.add(1)
[1, 5, 531, 5131, 53]
>>>
因此,它接受[1]处的任何元素,并将其放在队列的后面。我确信这是微不足道的,但作为Python新手,我似乎不明白为什么。
再次感谢您的帮助!谢谢。

在您的示例数据中,
[5,53,531,5131]
,您在
中表示的计算将如下所示:

# Append 1 to the end
--> [5, 53, 531, 5131, 1]

# The index for '1' is 4, so 'item' is 4.
# (4-1) // 2 = 1 (and 1 >= 0), so 'parent' is 1.
# The value at 'parent' is 53. 53 > 1 is true.
# So swap the value 53 with the value at the end of the list.
--> [5, 1, 531, 5131, 53]

# Now repeat, 'item' starts out at 1.
# The index at (1 - 1) // 2 = 0 (And 0 >=0) so 'parent' is 0.
# The value at index 0 is 5. 5 > 1 is true.
# So swap the value 5 with the value at 'item' (1) to get
--> [1, 5, 531, 5131, 53]
因此,这个结果从逻辑上遵循您编写
sift\u
的方式

标准库的
heapq.heapify
函数也会产生相同的结果:看起来这是优先级队列的正确行为:

In [18]: import heapq

In [19]: x = [5, 53, 531, 5131, 1]

In [20]: heapq.heapify(x)

In [21]: x
Out[21]: [1, 5, 531, 5131, 53]

堆要求比您想象的要宽松得多。重要的是,
pq[n]好的,谢谢你的帮助。我一定是想错了,如果它应该是这样工作的,那么我想我很好!
In [18]: import heapq

In [19]: x = [5, 53, 531, 5131, 1]

In [20]: heapq.heapify(x)

In [21]: x
Out[21]: [1, 5, 531, 5131, 53]