Python3优先级队列使用O(log(n))按值搜索和删除项目

2024-09-29 21:57:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在python 3中使用如下^{}实现一个priority queue

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))搜索和删除优先级队列中的项目

我想知道有没有办法做到这一点

有人能帮忙吗


Tags: fromselfreturnqueuevaluetopdefval

热门问题