2009-04-10

python里的最小堆

python的heapq这个模块实现了最小堆. 它也是一个优先队列.
这个堆其实是用列表这个基本的类型来实现的.
堆的操作很少:
1. 向堆插入一个元素: heappush(list, item)
2. 删除堆顶的元素: item = heappop(list)
3. 将一个列表转换成堆 heapify(list)

另外还有几个扩展的功能:
1. 删除堆顶的元素,然后插入一个新的元素: heapreplace(heap, item)
2. 返回最大的n个数: nlargest(n, heap)
3. 返回最小的n个数: nsmallest(n, heap)

>>> from heapq import *
>>> heap = [ 2,1,-1,9,8 ]
>>> heapify(heap)
>>> heap
[-1, 1, 2, 9, 8]
>>> heappush(heap, 3)
>>> heap
[-1, 1, 2, 9, 8, 3]
>>> heappush(heap, -2)
>>> heap
[-2, 1, -1, 9, 8, 3, 2]
>>> heappop(heap)
-2
>>> heap
[-1, 1, 2, 9, 8, 3]
>>> heapreplace(heap, 7)
-1
>>> heap
[1, 7, 2, 9, 8, 3]
>>> nlargest(3, heap)
[9, 8, 7]
>>> nsmallest(3, heap)
[1, 2, 3]
>>> heap
[1, 7, 2, 9, 8, 3]
>>>


转载请注明出处 http://fornote.blogspot.com

没有评论:

发表评论