Python利用heapq实现一个优先级队列
2017-04-02 10:43
761 查看
实现一个优先级队列,每次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实现prim算法以及优先级队列
- 利用redis的订阅和发布来实现实时监控的一个DEMO(Python版本)
- 两个堆栈实现一个队列 , 利用两个队列实现一个堆栈(Java)
- (第7讲)利用双向链表实现双端队列、优先级队列(有序数组实现、有序链表实现)
- 利用python的双向队列(Deque)数据结构实现回文检测的算法
- 一个C优先级队列实现
- W. :利用最小优先级队列实现对k个已序队列的合并排序。习题6.5-8
- leetcode_107. Binary Tree Level Order Traversal II 二叉树层次遍历,利用python的list特性实现队列功能
- 一个简单的优先级队列实现
- GO语言heap剖析及利用heap实现优先级队列
- 要求顺序循环队不损失一个空间,全部能够得到有效利用,试采用设置标志位tag的方法解决“假溢出”问题,实现顺序循环队列算法
- Python实现优先级队列结构的方法详解
- C++利用模板实现一个队列
- 《算法》第一章——利用两个栈实现一个队列的push和pop操作
- python-heapq-优先级队列-堆
- 利用redis实现带优先级的消息队列
- 利用两个队列实现一个栈(C++版)
- python利用redis构成一个队列
- 编程珠玑: 14章 堆 14.2实现一个优先级队列,返回数组中最小值 -------解题总结
- 利用优先级队列实现事件驱动模拟