Python实现优先队列范例
本文自定义了一个优先队列的Python类,通过类实现优先队列的相关数据结构,包括push和pop操作
""" 皮蛋编程(https://www.pidancode.com) 创建日期:2022/4/27 功能描述:Python实现优先队列范例 """ import heapq class PriorityQueue: def __init__(self): self._queue = [] self._index = 0 def push(self, item, priority): heapq.heappush(self._queue, (-priority, self._index, item)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1] # Example use class Item: def __init__(self, name): self.name = name def __repr__(self): return 'Item({!r})'.format(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("Should be bar:", q.pop()) print("Should be spam:", q.pop()) print("Should be foo:", q.pop()) print("Should be grok:", q.pop())
输出:
Should be bar: Item('bar') Should be spam: Item('spam') Should be foo: Item('foo') Should be grok: Item('grok')
代码在Python3.9下测试通过。
相关文章