当前位置:脚本大全 > > 正文

python实现栈和队列(Python利用heapq实现一个优先级队列的方法)

时间:2022-04-01 01:17:39类别:脚本大全

python实现栈和队列

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

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

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 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实现栈和队列(Python利用heapq实现一个优先级队列的方法)

    以上这篇python利用heapq实现一个优先级队列的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持开心学习网。

    原文链接:https://blog.csdn.net/Jmiew123/article/details/68951054

    上一篇下一篇

    猜您喜欢

    热门推荐