python 从优先级队列中删除项目

llmtgqce  于 5个月前  发布在  Python
关注(0)|答案(6)|浏览(70)

在Python中,heapq模块提供了一个优先级队列。
它有插入和弹出项的方法。
如何从队列中删除插入的不是最低优先级的项?
(也欢迎使用其他收藏品来做这件事的替代食谱)

nfs0ujit

nfs0ujit1#

heapq模块使用标准的Python列表作为底层数据结构,因此在此之后,您可以再次使用标准的list方法remove()heapify()。请注意,这将需要线性时间。

# Create example data and heapify
a = range(10)
a.reverse()
heapq.heapify(a)
print a

# remove an element and heapify again
a.remove(5)
heapq.heapify(a)
print a

字符串
你可以通过使用未文档化的函数heapify._siftup()来再次提高堆化的性能,但是整个过程仍然是O(n),因为list.remove()是O(n)。

hkmswyz6

hkmswyz62#

如果您知道要删除的项目的位置,可以执行以下操作:

a[k] = a.pop()
heapq.heapify(a)

字符串
第一步现在是O(1)时间,第二步可以通过使用未记录的数据来实现O(log(N))。当然,如果你还没有k,它仍然是O(N)。

r7s23pms

r7s23pms3#

这个log(N)函数对我来说很有用:

def heapq_remove(heap, index):
    """Remove item from heap"""

    # Move slot to be removed to top of heap
    while index > 0:
        up = (index + 1) / 2 - 1
        heap[index] = heap[up]
        index = up

    # Remove top of heap and restore heap property
    heapq.heappop(heap)

字符串

6g8kf2rb

6g8kf2rb4#

有一种叫做treap的数据结构,它是一个优先级队列和二叉树的组合。(树堆)。它允许log-n搜索,这可能会对你有所帮助。
有一个Python treap implementation on PyPi..;)

n1bvdmb6

n1bvdmb65#

我在使用search algorithmsproject上遇到了这个问题,下面是答案:

queue_name = PriorityQueue()

queue_name.queue.remove(item_to_be_removed)

字符串
假设你有一个tuple作为一个项目,那么一个例子是:

queue_name.queue.remove((number, item_name))

jljoyd4f

jljoyd4f6#

有一种方法使用内部的_siftup_siftdown。你需要同时使用这两个,因为在交换之后,元素可能需要向下游泳,因为它可能需要向上浮动。正如@rayryeng指出的,index操作使算法O(n)。

import heapq

# The removal function using internal functions
def remove_item(heap, val):
    if not heap:
        return

    try:
        i = heap.index(val)
    except ValueError:
        return

    if i < len(heap) - 1:
        heap[i] = heap[-1]

    heap.pop()
    if i < len(heap):
        heapq._siftup(heap, i)
        heapq._siftdown(heap, 0, i)

# Initial state
a = range(30)
a.reverse()
heapq.heapify(a)
print(a)

# The removal
remove_item(a, 15)
print(a)

字符串
荣誉给邓肯:https://stackoverflow.com/a/10163422/292502

相关问题