1.下面是cookbook的原代码,利用heapq模块实现了一个优先级队列,每次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]
使用方式:
>>> 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)
>>> q.pop()
Item('bar')
>>> q.pop()
Item('spam')
>>> q.pop()
Item('foo')
>>> q.pop()
Item('grok')
那么,问题来了,heappop()函数会优先删除第一个元素,然后才是删除最小的元素,按照上面的使用,应该优先删除foo,然后才是最小的bar吧?这段代码是从哪里将它进行排序了么?
下面是普通的例子:
In [1]: x = [(-1, 0, 'for'), (-5, 1, 'bar'), (-4, 2, 'spam'), (-1, 3, 'grok')]
In [2]: import heapq
In [3]: heapq.heappop(x)[-1]
Out[3]: 'for'
In [4]: heapq.heappop(x)[-1]
Out[4]: 'bar'
In [5]: heapq.heappop(x)[-1]
Out[5]: 'spam'
In [6]: heapq.heappop(x)[-1]
Out[6]: 'grok'
我的背景是自学 + google,基本功不扎实,还请赐教。
你的例子里缺了一步:
书中的例子里每一步
heappush()
都会进行排序。