相关疑难解决方法(0)

我在Python中使用什么来实现最大堆实现?

Python包含用于min-sheaps的heapq模块,但我需要一个最大堆.我应该在Python中使用什么来实现max-heap实现?

python heap recursive-datastructures data-structures

197
推荐指数
10
解决办法
10万
查看次数

Python中内置的最大堆API

默认heapq是min队列实现,并想知道是否有最大队列选项?谢谢.

我尝试使用_heapify_max作为最大堆的解决方案,但是如何处理动态推/弹元素?似乎_heapify_max只能在初始化时使用.

import heapq

def heapsort(iterable):
    h = []
    for value in iterable:
        heapq.heappush(h, value)
    return [heapq.heappop(h) for i in range(len(h))]

if __name__ == "__main__":

    print heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
Run Code Online (Sandbox Code Playgroud)

编辑,尝试_heapify_max似乎不适用于动态推/弹元素.我尝试两种方法输出相同,两个输出都是,[0,1,2,3,4,5,6,7,8,9].

def heapsort(iterable):
    h = []
    for value in iterable:
        heapq.heappush(h, value)
    return [heapq.heappop(h) for i in range(len(h))]

def heapsort2(iterable):
    h = []
    heapq._heapify_max(h)
    for value in iterable:
        heapq.heappush(h, value)
    return [heapq.heappop(h) for i in range(len(h))]

if __name__ == "__main__":

    print heapsort([1, 3, 5, …
Run Code Online (Sandbox Code Playgroud)

python algorithm queue priority-queue

23
推荐指数
2
解决办法
1万
查看次数