从维基百科
二叉堆的定义来看,sift-up也称为up-heap操作,sift-down称为down-heap。
所以在堆(完全二叉树)中,up表示从叶到根,down表示从根到叶。
但在Python中,情况似乎恰恰相反。siftup我对and的含义感到困惑siftdown,并且在第一次使用时被误用。
_siftdown以下是和_siftup中的 python 版本实现heapq:
# 'heap' is a heap at all indices >= startpos, except possibly for pos. pos
# is the index of a leaf with a possibly out-of-order value. Restore the
# heap invariant.
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding …Run Code Online (Sandbox Code Playgroud) 我将一个空列表UNVISITED转换为堆,例如:
UNVISITED = []
heapq.heappush(UNVISITED, (a.f, a))
Run Code Online (Sandbox Code Playgroud)
a我推送的对象(从类实例化)具有以下字段:
class UNVISITEDNode():
def __init__(self, value1, value2 , value3, value4, value5):
self.q = value1
self.h = value2
self.g = value3
self.f = value4
self.p = value5
Run Code Online (Sandbox Code Playgroud)
在整个算法中,valueX无论何时需要,我都会不断修改堆中已有对象的任何内容,例如:
for i in range(len(UNVISITED)):
UNVISITED[i][1].q = newvalue1
UNVISITED[i][1].h = newvalue2
UNVISITED[i][1].g = newvalue3
UNVISITED[i][1].f = newvalue4
UNVISITED[i][1].p = newvalue5
Run Code Online (Sandbox Code Playgroud)
因为(或者我认为,如果我做错了,请纠正我)f像现在所做的那样修改值不会更改影响堆排序的值,因此我直接尝试进行修改UNVISITED[i][0](这是a.f第二次通过的内容)创建堆时第二个参数的一部分)。
[问题]->然后,我被告知此值不允许修改:
UNVISITED[i][0] = newvalue4
*Traceback (most recent call last):
File "/home/daniel/pycharm-2017.3.3/helpers/pydev/
_pydevd_bundle/pydevd_exec.py", line 3, in …Run Code Online (Sandbox Code Playgroud)