当前位置: 首页 > 后端技术 > Python

Python实现一个优先级队列_0

时间:2023-03-26 19:22:24 Python

实现一个优先级队列问题如何实现一个按优先级排序的队列,每次执行pop返回优先级最高的元素?这里的解决方案参考了Python提供的heapq模块。importheapqclassPriorityQueue(object):'''实现优先级队列,每次执行pop操作时返回优先级最高的元素'''def__init__(self):#创建初始队列和索引(保证priority是重复的,可以用order来区分)self._queue=[]self._index=0defpush(self,item,priority):#这里插入的第二个参数包括priority,index,heapq.heappush(self._queue,(-priority,self._index,item))self._index+=1defpop(self):returnheapq.heappop(self._queue)[-1]方法用法:classItem(object):def__init__(self,名称):self.name=namedef__repr__(self):return'Item({!r})'.format(self.name)q=PriorityQueue()q.push(Ite??m('foo'),1)问。push(Ite??m('bar'),5)q.push(Ite??m('spam'),4)q.push(Ite??m('grok'),1)print(q.pop())#Item('bar')print(q.pop())#item('spam')print(q.pop())#item('foo')print(q.pop())#item('grok')可以观察到这里顺带一提,第一个pop()返回的是优先级最高的元素。另外,对于实例中优先级相同的元素*foo和grok),pop操作返回的结果是按照插入队列的顺序排列的。这里的代码分析主要是指heapq模块的使用。heapq.heappush()和heapq.heappop()分别插入和删除队列_queue上的第一个元素,队列_queue保留优先级最高的第一个元素。heappop()函数总是返回“最小”的元素,这是保证队列pop操作返回正确元素的关键。在上面的代码中,队列包含(-priority,index,item)元组。负优先级的目的是使元素从高优先级到低优先级排序。索引的作用是保证相同优先级的元素排序。递增的索引变量保留在这里以确保它们按照插入的顺序排序。举个例子来说明索引变量的作用。假设Item实例不支持排序:>>>a=Item('foo')>>>b=Item('bar')>>>a",line1,inTypeError:unorderabletypes:Item()>>a=(1,Item('foo'))>>>b=(5,Item('bar'))>>>a>>c=(1,Item('grok'))>>>a",line1,inTypeError:unorderabletypes:Item()<在Item()中引入索引变量可以解决这个问题,因为索引是递增的,不能相同。Python元组比较的操作是前面比较的结果不会比较后面的,所以这里形成的元组是(priority,index,item):>>>a=(1,0,Item('foo'))>>>b=(5,1,Item('bar'))>>>c=(1,2,Item('grok'))>>>a>>a