PythonCookbook 笔记:简单实现优先级队列

Python 简单实现优先级队列

"""
自定义优先级队列
"""

import heapq


class PriorityQueue:
    """
    优先级队列
    """

    def __init__(self):
        self._queue = []
        self._index = 0

    def push(self, item, priority):
        """
        此处使用元组来作为对 item 进行封装,实际上是利用了元组的可比较特性
        """

        heapq.heappush(self._queue, (-priority, self._index, item))
        self._index += 1

    def pop(self):
        return heapq.heappop(self._queue)[-1]


class Item:

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return f'Item({self.name})'


q = PriorityQueue()
q.push(Item('foo'), 1)
q.push(Item('bar'), 5)
q.push(Item('spam'), 4)
q.push(Item('grok'), 1)


print(q.pop())
print(q.pop())
print(q.pop())
print(q.pop())

# 输出
# > Item(bar)
# > Item(spam)
# > Item(foo)
# > Item(grok)

你可能感兴趣的:(python,开发语言,Python,Cookbook)