首页 > 解决方案 > Python 3 - 优先队列 - 使用 O(log(n)) 按值搜索和删除项目

问题描述

我正在使用这样priority queue的python 3实现a-queue.PriorityQueue

from queue import PriorityQueue

class PqElement(object):
    def __init__(self, value: int):
        self.val = value

    #Custom Compare Function (less than or equsal)
    def __lt__(self, other):
        """self < obj."""
        return self.val > other.val

    #Print each element function
    def __repr__(self):
        return f'PQE:{self.val}'

#Usage-
pq = PriorityQueue()
pq.put(PqElement(v))       # Add Item      - O(Log(n))
topValue = pq.get()        # Pop top item  - O(1)
topValue = pq.queue[0].val # Get top value - O(1)
pqSize = pq.qsize()        # Provide Queue Size - O(1)
isEmpty = pq.empty()       # Is PQ is empty

我喜欢使用 O(log(n)) 搜索和删除优先级队列中的项目。

我想知道是否有任何方法可以做到这一点?

有人可以帮忙吗?

标签: pythonpython-3.xqueuepriority-queue

解决方案


推荐阅读