一个队列至少满足2个方法,put和get.
借助最小堆来实现.
这里按"值越大优先级越高"的顺序.
#coding=utf-8 from heapq import heappush, heappop class PriorityQueue: def __init__(self): self._queue = [] def put(self, item, priority): heappush(self._queue, (-priority, item)) def get(self): return heappop(self._queue)[-1] q = PriorityQueue() q.put('world', 1) q.put('hello', 2) print q.get() print q.get()
时间: 2024-10-18 22:50:10