试图理解 python 中的最大堆。一旦我弹出元素,元素就会被排列为最小堆。
import heapq
a=[3,2,1,4,9]
heapq._heapify_max(a) # This createa a binary tree with max val at the root
print(a) # This should be [9,4,3,2,1]
heapq.heappop(a) # when poped state of a will be [4,....]
print(a) # But a is [1,4,2,3] -- Why?
heapq.heappop(a)
print(a)
b=[3,2,1,4,9]
heapq.heapify(b)
print(b) # [1,2,3,4,9]
heapq.heappop(b) # pops 1 out
print(b) # [2,4,3,9]
heapq.heappop(b) # pops 2 out
print(b) # [3,4,9]
To keep the state of max heap I am currently using maxheap inside a …Run Code Online (Sandbox Code Playgroud)