网络编程
位置:首页>> 网络编程>> Python编程>> Python利用heapq实现一个优先级队列的方法

Python利用heapq实现一个优先级队列的方法

作者:LazyCat_CiCi  发布时间:2021-08-05 06:28:48 

标签:Python,heapq,优先,队列

实现一个优先级队列,每次pop的元素要是优先级高的元素,由于heapq.heapify(list)默认构建一个小顶堆,因此要将priority变为相反数再push,代码如下:


import heapq
class PriorityQueue(object):
 """实现一个优先级队列,每次pop优先级最高的元素"""
 def __init__(self):
   self._queue = []
   self._index = 0
 def push(self,item,priority):
   heapq.heappush(self._queue,(-priority,self._index,item))#将priority和index结合使用,在priority相同的时候比较index,pop先进入队列的元素
   self._index += 1
 def pop(self):
   return heapq.heappop(self._queue)[-1]
if __name__ == '__main__':
 pqueue = PriorityQueue()
 pqueue.push('d',4)
 pqueue.push('f',3)
 pqueue.push('a',6)
 pqueue.push('s',2)
 print(pqueue.pop())
 print(pqueue.pop())
 print(pqueue.pop())

Python利用heapq实现一个优先级队列的方法

来源:https://blog.csdn.net/Jmiew123/article/details/68951054

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com