在 python 中查看堆
查看 heapq 库创建的 python 堆的官方方法是什么?现在我拥有的
def heappeak(heap):
smallest = heappop(heap)
heappush(heap, smallest)
return smallest
可以说不是很好。我是否可以始终假设 heap[0]
是堆的顶部并使用它?或者这会假设太多的底层实现吗?
What is the official way of peeking in a python heap as created by the heapq libs? Right now I have
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您可以做出这个假设,因为它在文档中进行了说明:
(这可能就是没有
peek
功能的原因:没有必要。)Yes, you can make this assumption, because it is stated in the documentation:
(And that's probably the reason there is no
peek
function: there is no need for it.)如果您使用的是 Python 2.4 或更高版本,您还可以使用 heapq.nsmallest()。
If you're using Python 2.4 or newer, you can also use heapq.nsmallest().
Python3 文档明确指出可以使用 heap[0] 来查看最小的元素不弹出。
注意:如果您想保持最大堆,可以使用负数。
Python3 documentation clearly states that you can use heap[0] to peek the smallest element without popping.
Note: You can use negative notation if you want to maintain the max heap.