2014年03月05日 星期三 09:36
优先级队列是在普通FIFO队列的基础上,增加了优先级的权重,优先级高的元素,将优先出队列,从而得到优先处理。
代码示例如下:
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] class Item: def __init__(self, name): self.name = name def __repr__(self): return 'Item({!r})'.format(self.name) pq = PriorityQueue() pq.push(Item('laomeng'), 1) pq.push(Item('laozhang'), 10) pq.push(Item('laoli'), 3) pq.push(Item('laoliu'), 5) print(pq.pop()) print(pq.pop()) print(pq.pop()) print(pq.pop())
参考资料:
Zeuux © 2024
京ICP备05028076号