我正在尝试使用自定义排序谓词构建堆.由于进入它的值是'用户定义'类型,我无法修改它们的内置比较谓词.
有没有办法做这样的事情:
h = heapq.heapify([...], key=my_lt_pred)
h = heapq.heappush(h, key=my_lt_pred)
Run Code Online (Sandbox Code Playgroud)
或者甚至更好,我可以将heapq函数包装在我自己的容器中,这样我就不需要继续传递谓词了.
默认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) max()从列表返回最大元素的函数...在Big O表示法方面,它的运行时间(在Python 3中)是多少?
如何使用Queue.PriorityQueue作为maxheap python?
Queue.PriorityQueue 的默认实现是 minheap,文档中也没有提及是否可以用于 maxheap。
有人可以告诉是否可以使用 Queue.PriorityQueue 作为 maxheap 吗
可能重复:
我在Python中使用什么来实现最大堆实现?
我试图以某种方式实现python的heapq但是对于max-heap.一个解决方案是使用(-1)和多个队列号,但这对我没有帮助,因为我需要将URL存储在堆中.所以我想要一个max heapq,我可以弹出最大的值.
我一直在实现自己的堆模块,以帮助我理解堆数据结构.我理解它们是如何工作和管理的,但我的实现比标准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 ×6
algorithm ×2
python-3.x ×2
big-o ×1
binary-heap ×1
containers ×1
dictionary ×1
heap ×1
heapsort ×1
max-heap ×1
min-heap ×1
performance ×1
python-2.7 ×1
queue ×1
sorting ×1