首先我通过使用创建了a&b的两个结果heapq.merge,但是在使用mergea&b之后,我发现a的列表是空的。
>>> a=merge([1,2],[3,4])
>>> b=merge([4,5],[6,7])
>>> list(a)
[1, 2, 3, 4]
>>> merge(a,b)
<generator object merge at 0x365c370>
>>> list(a)
[]
>>>
Run Code Online (Sandbox Code Playgroud)
最后的结果list(a)是空的,为什么merge(a,b)改a?
在 Python 3 中,我像这样使用 heapq:
import heapq
heap = [3]
heapq.heapify(heap)
heapq.heappush(heap, 5)
# Push more values...
# I can iterate heap like so, but by the end it will be empty:
while (heap):
curr = heapq.heappop(heap)
# Do whatever with curr
Run Code Online (Sandbox Code Playgroud)
有没有办法迭代 heapq 以便我按排序顺序获取值而不会改变 heapq/丢失数据?
如果没有,我怎样才能有效地模仿所需的行为?
我想出的解决方案是创建一个临时堆,在我从原始堆中弹出时推送到它,一旦我完成迭代,将原始堆设置为等于临时堆。
当然这不是很有效,而且改变了原始堆引用的对象。
temp = []
heapq.heapify(temp)
while(heap):
curr = heapq.heappop(heap)
heapq.heappush(temp, curr)
# Do whatever with curr
heap = temp
Run Code Online (Sandbox Code Playgroud) 每个人都说如果你把元组推入heapq,它会以第一个参数作为比较因子。
但事实并非如此!我很好奇我的代码有什么问题?
for task_name, counter in tasks_counter.items():
heappush(tasks_q, (-int(counter), task_name, counter))
heapify(tasks_q)
while tasks_q:
print(tasks_q.pop())
Run Code Online (Sandbox Code Playgroud)
(-1, 'G', 1)
(-1, 'F', 1)
(-1, 'E', 1)
(-1, 'D', 1)
(-1, 'C', 1)
(-1, 'B', 1)
(-6, 'A', 6)
Run Code Online (Sandbox Code Playgroud)
我觉得我应该先拿到有价值的东西A吧?但事实并非如此。
在 Python 中使用内置优先级队列的任何替代解决方案?
试图理解 python 中的最大堆。一旦我弹出元素,元素就会被排列为最小堆。
import heapq
a=[3,2,1,4,9]
heapq._heapify_max(a) # This createa a binary tree with max val at the root
print(a) # This should be [9,4,3,2,1]
heapq.heappop(a) # when poped state of a will be [4,....]
print(a) # But a is [1,4,2,3] -- Why?
heapq.heappop(a)
print(a)
b=[3,2,1,4,9]
heapq.heapify(b)
print(b) # [1,2,3,4,9]
heapq.heappop(b) # pops 1 out
print(b) # [2,4,3,9]
heapq.heappop(b) # pops 2 out
print(b) # [3,4,9]
To keep the state of max heap I am currently using maxheap inside a …Run Code Online (Sandbox Code Playgroud)