需求:我们想要实现一个队列,他能够以给定的优先级来对元素排序,且每次pop操作时都会返回优先级最高的那个元素。
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] #heapq.heappop 是从小到大弹出元素
#对以上队列的使用:
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)
In [12]: q.pop()
Out[12]: Item('bar') #首先弹出优先级最高为5的 bar
In [13]: q.pop()
Out[13]: Item('spam') #弹出优先级第二高的 spam
In [14]: q.pop()
Out[14]: Item('foo')
In [15]: q.pop()
Out[15]: Item('grok')
In [16]: q.pop() #也会越界报错
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-16-a75d510a0910> in <module>
----> 1 q.pop()
<ipython-input-2-3082b7808476> in pop(self)
10
11 def pop(self):
---> 12 return heapq.heappop(self._queue)[-1]
13
IndexError: index out of range