python最大堆_Python中内置的最大堆API

最新的cpython源中有一个_heappop_max函数,您可能会发现它很有用:def _heappop_max(heap):

"""Maxheap version of a heappop."""

lastelt = heap.pop() # raises appropriate IndexError if heap is empty

if heap:

returnitem = heap[0]

heap[0] = lastelt

heapq._siftup_max(heap, 0)

return returnitem

return lastelt

如果使用heapq._siftdown_max更改heappush逻辑,则应获得所需的输出:def _heappush_max(heap, item):

heap.append(item)

heapq._siftdown_max(heap, 0, len(heap)-1)

def _heappop_max(heap):

"""Maxheap version of a heappop."""

lastelt = heap.pop() # raises appropriate IndexError if heap is empty

if heap:

returnitem = heap[0]

heap[0] = lastelt

heapq._siftup_max(heap, 0)

return returnitem

return lastelt

def heapsort2(iterable):

h = []

heapq._heapify_max(h)

for value in iterable:

_heappush_max(h, value)

return [_heappop_max(h) for i in range(len(h))]

输出:In [14]: heapsort2([1,3,6,2,7,9,0,4,5,8])

Out[14]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

In [15]: heapsort2([7, 8, 9, 6, 4, 2, 3, 5, 1, 0])

Out[15]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

In [16]: heapsort2([19,13,15,17,11,10,14,20,18])

Out[16]: [20, 19, 18, 17, 15, 14, 13, 11, 10]

In [17]: heapsort2(["foo","bar","foobar","baz"])

Out[17]: ['foobar', 'foo', 'baz', 'bar']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值