【发布时间】:2020-05-05 18:34:04
【问题描述】:
以官方heapq为例:
>>> heap = []
>>> data = [(1, 'J'), (4, 'N'), (3, 'H'), (2, 'O')]
>>> for item in data:
... heappush(heap, item)
...
>>> while heap:
... print(heappop(heap)[1])
J
O
H
N
我想进一步实现一个高效的selective_push,这样
- selective_push((1, 'M')) 等价于 heappush,因为 'M' 不在堆中
- selective_push((3.5, 'N')) 等价于 heap[2]= (3.5, 'N'); heapify(heap) 自 3.5
- selective_push((4.5, 'N')) 自 4.5>4 起什么也不做
以下实现解释了目标但速度很慢:
def selective_push(heap,s):
NotFound=True
for i in range(len(heap)): #linear search
if heap[i][1]==s[1]:
if s[0]<heap[i][0]:
heap[i]=s #replacement
heapify(heap)
NotFound=False
break
if NotFound:
heappush(heap,s)
我认为由于线性搜索,它很慢,这破坏了heapq.push 的 log(n) 复杂性。替换率低,但始终执行线性搜索。
【问题讨论】:
标签: python search replace heapq