相关疑难解决方法(0)

具有自定义比较谓词的heapq

我正在尝试使用自定义排序谓词构建堆.由于进入它的值是'用户定义'类型,我无法修改它们的内置比较谓词.

有没有办法做这样的事情:

h = heapq.heapify([...], key=my_lt_pred)
h = heapq.heappush(h, key=my_lt_pred)
Run Code Online (Sandbox Code Playgroud)

或者甚至更好,我可以将heapq函数包装在我自己的容器中,这样我就不需要继续传递谓词了.

python sorting algorithm containers dictionary

61
推荐指数
4
解决办法
5万
查看次数

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万
查看次数

Python的最大功能效率如何

max()从列表返回最大元素的函数...在Big O表示法方面,它的运行时间(在Python 3中)是多少?

python performance big-o python-3.x

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

如何使用 Queue.PriorityQueue 作为 maxheap python

如何使用Queue.PriorityQueue作为maxheap python?

Queue.PriorityQueue 的默认实现是 minheap,文档中也没有提及是否可以用于 maxheap。

有人可以告诉是否可以使用 Queue.PriorityQueue 作为 maxheap 吗

python heap priority-queue python-2.7 python-3.x

6
推荐指数
1
解决办法
7633
查看次数

来自heapq python的pop max值,Python中是否有最大堆?

可能重复:
我在Python中使用什么来实现最大堆实现?

我试图以某种方式实现python的heapq但是对于max-heap.一个解决方案是使用(-1)和多个队列号,但这对我没有帮助,因为我需要将URL存储在堆中.所以我想要一个max heapq,我可以弹出最大的值.

python min-heap max-heap

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

为什么二进制堆的实现比Python的stdlib慢?

我一直在实现自己的堆模块,以帮助我理解堆数据结构.我理解它们是如何工作和管理的,但我的实现比标准python heapq模块慢得多,同时执行堆排序(对于大小为100,000的列表,heapq需要0.6s而我的代码需要2s(原来是2.6s,切断它)通过从percDown中取出len()语句并传递长度来减少到2s所以每次方法调用自身时都不必计算len.这是我的实现:

def percDown(lst, start, end, node):
    #Moves given node down the heap, starting at index start, until the heap property is
    #satisfied (all children must be larger than their parent)
    iChild = 2 * start + 1
    i = start
    # if the node has reached the end of the heap (i.e. no children left),
    # return its index (we are done)
    if iChild > end - 1:
        return start
    #if the second child exists and is smaller than …
Run Code Online (Sandbox Code Playgroud)

python binary-heap heapsort

1
推荐指数
1
解决办法
436
查看次数