在 python 堆中偷看

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1750991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:59:40  来源:igfitidea点击:

Peeking in a heap in python

pythonheappeek

提问by Thomas

What is the official way of peeking in a python heap as created by the heapq libs? Right now I have

查看由 heapq 库创建的 python 堆的官方方法是什么?现在我有

def heappeak(heap):
  smallest = heappop(heap)
  heappush(heap, smallest)
  return smallest

which is arguably, not very nice. Can I always assume that heap[0]is the top of the heap and use that? Or would that assume too much of the underlying implementation?

这可以说不是很好。我可以总是假设这heap[0]是堆的顶部并使用它吗?或者这是否会假设太多的底层实现?

回答by Stephan202

Yes, you can make this assumption, because it is stated in the documentation:

是的,您可以做出这个假设,因为它在文档中说明

Heaps are arrays for which heap[k] <= heap[2*k+1]and heap[k] <= heap[2*k+2]for all k, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that heap[0]is always its smallest element.

堆是数组,其中heap[k] <= heap[2*k+1]heap[k] <= heap[2*k+2]所有k,从零开始计数元素。为了比较,不存在的元素被认为是无限的。堆的有趣特性是它 heap[0]总是最小的元素。

(And that's probably the reason there is no peekfunction: there is no need for it.)

(这可能就是没有peek函数的原因:不需要它。)

回答by DannyTree

If you're using Python 2.4 or newer, you can also use heapq.nsmallest().

如果您使用 Python 2.4 或更新版本,您还可以使用 heapq.nsmallest()。