Python Cookbook - 实现优先队列代码块(源码+验证)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Vincent_Xupt/article/details/80212082
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(object):
    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)
for i in range(4):
    print(q._queue)
    print(q.pop(),end='\n\n')

运行结果:

[(-5, 1, Item: 'bar'), (-1, 0, Item: 'foo'), (-4, 2, Item: 'spam'), (-1, 3, Item: 'grok')]
Item: 'bar'

[(-4, 2, Item: 'spam'), (-1, 0, Item: 'foo'), (-1, 3, Item: 'grok')]
Item: 'spam'

[(-1, 0, Item: 'foo'), (-1, 3, Item: 'grok')]
Item: 'foo'

[(-1, 3, Item: 'grok')]
Item: 'grok'

猜你喜欢

转载自blog.csdn.net/Vincent_Xupt/article/details/80212082
今日推荐