maxHeap python 在弹出元素后转换为最小堆
试图理解 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 while loop
while count_heap or q:
heapq._heapify_max(count_heap)
一旦我在 python 中弹出一个元素,最大堆是否会转换回最小堆?
Trying to understand the max heap in python. Once I pop the element the elements are arranged as min heap.
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 while loop
while count_heap or q:
heapq._heapify_max(count_heap)
Does max heap converts back to min heap once I pop an element in python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有特殊的“属性”将堆标记为最大堆。
heapq 中的默认值是 min-heap,所有常用操作(如 heappop)都意味着 min-heap。
因此,您必须再次使用带下划线的函数版本:
PS 老技巧,也许在
*_max
函数出现之前:只需对初始列表中的数字求反并推送/弹出值。There is no special "property" to mark heap as max-heap.
Default in
heapq
is min-heap, all usual operations (likeheappop
) imply min-heap.So you have to use underscored function versions again:
P.S. Old trick, perhaps before
*_max
functions appearance: just negate numbers in the initial list and pushed/popped values.