在Python堆里偷看

2024-10-03 15:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在heapq libs创建的python堆中查看的正式方式是什么?现在我有

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

可以说,不是很好。我能一直假设heap[0]是堆的顶部并使用它吗?或者,这会假设基础实现太多吗?


Tags: returndef方式基础libsheapheapqsmallest
2条回答

如果您使用的是Python2.4或更新版本,也可以使用heapq.nsmalest()。

是的,您可以做出这样的假设,因为它是在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.

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

相关问题 更多 >