Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的heappush行为_Python_Heap_Heapq - Fatal编程技术网

python中的heappush行为

python中的heappush行为,python,heap,heapq,Python,Heap,Heapq,我有一个数组arr=[1,2,1,3] 当我使用heappush函数将数组元素按原样推入堆中时,其顺序与数组中的顺序完全相同: arr = [1,2,1,3] heap = [] for i in range(len(arr)): heapq.heappush(heap, arr[i]) print(heap) Result: [1, 2, 1, 3] 现在,如果我推送arr元素的负值,堆将按其所提供的方式排序 arr = [1,2,1,3] heap = [] for i in r

我有一个数组arr=[1,2,1,3]

当我使用heappush函数将数组元素按原样推入堆中时,其顺序与数组中的顺序完全相同:

arr = [1,2,1,3]
heap = []
for i in range(len(arr)):
    heapq.heappush(heap, arr[i])
print(heap)

Result: [1, 2, 1, 3]
现在,如果我推送arr元素的负值,堆将按其所提供的方式排序

arr = [1,2,1,3]
heap = []
for i in range(len(arr)):
     heapq.heappush(heap,  - arr[i])    <---- Here
print(heap)

Result: [-3, -2, -1, -1]
arr=[1,2,1,3]
堆=[]
对于范围内的i(len(arr)):

heapq.heappush(heap,-arr[i])这被称为
堆不变量
,您也可以在中看到这一点,其中说明:


堆是二叉树,每个父节点的值都小于或等于其任何子节点。这个实现使用的数组
heap[k]你看到这个答案了吗?堆的内容不应该被排序。这就是为什么有一个单独的术语“堆”,而不是仅仅称它们为“排序列表”。请注意,它也不必是二叉树。您可以使用更高级的树,但代价是使实现更加复杂。这样做的好处是更好的缓存局部性。
inf = float('inf')
arr = [1, 2, 1, 3]

for i in range(len(arr)):
    x = arr[i]
    try:
        y = arr[2 * i + 1]
    except IndexError:
        y = inf
    print('x <= y is {}'.format(x <= y))

x <= y is True
x <= y is True
x <= y is True
x <= y is True