maxHeap python 在弹出元素后转换为最小堆

发布于 2025-01-14 08:05:02 字数 678 浏览 0 评论 0原文

试图理解 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月苍老的讽刺 2025-01-21 08:05:02

没有特殊的“属性”将堆标记为最大堆。

heapq 中的默认值是 min-heap,所有常用操作(如 heappop)都意味着 min-heap。

因此,您必须再次使用带下划线的函数版本:

heapq._heappop_max(a) 


[9, 4, 1, 3, 2]
[4, 3, 1, 2]
[3, 2, 1]

PS 老技巧,也许在 *_max 函数出现之前:只需对初始列表中的数字求反并推送/弹出值。

There is no special "property" to mark heap as max-heap.

Default in heapq is min-heap, all usual operations (like heappop) imply min-heap.

So you have to use underscored function versions again:

heapq._heappop_max(a) 


[9, 4, 1, 3, 2]
[4, 3, 1, 2]
[3, 2, 1]

P.S. Old trick, perhaps before *_max functions appearance: just negate numbers in the initial list and pushed/popped values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文