在 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
Peeking in a heap in python
提问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]
andheap[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 thatheap[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 peek
function: 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()。