飘逸的python - 实现一个极简的优先队列

一个队列至少满足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()


posted @ 2017-05-26 14:09  yfceshi  阅读(288)  评论(0编辑  收藏  举报