Python cookbook(数据结构与算法)实现优先级队列的方法示例


Posted in Python onFebruary 18, 2018

本文实例讲述了Python实现优先级队列的方法。分享给大家供大家参考,具体如下:

问题:要实现一个队列,它能够以给定的优先级对元素排序,且每次pop操作时都会返回优先级最高的那个元素;

解决方案:采用heapq模块实现一个简单的优先级队列

# example.py
#
# Example of a priority queue
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]
# Example use
class Item:
  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)
print("Should be bar:", q.pop())
print("Should be spam:", q.pop())
print("Should be foo:", q.pop())
print("Should be grok:", q.pop())
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
Should be bar: Item('bar')
Should be spam: Item('spam')
Should be foo: Item('foo')
Should be grok: Item('grok')
>>>

可以看出:第一次执行pop()操作时返回的元素具有最高的优先级;对于相同优先级的两个元素(foo和gork)返回的顺序同它们插入到队列时的顺序相同。

在这段代码中,队列以元组(-priority, self._index, item)的形式组成,priority取负值是为了队列按照从高到低的顺序排列,这和堆默认的从小到大的排序相反。

变量index的作用是对相同优先级的元素以适当的顺序排列,特别对同优先级的元素间做比较操作时扮演了重要的角色。

Item实例无法进行次序比较:

a=Item('foo')
b=Item('bar')
print('a<b: ',a<b)
>>> 
Traceback (most recent call last):
 File "D:\4autotests\02script\python-cookbook\python-cookbook-master\src\1\5.implementing_a_priority_queue\example.py", line 27, in <module>
  print('a<b: ',a<b)
TypeError: unorderable types: Item() < Item()
>>>

如果以元组(priority,  item)的形式来表示元素,只要优先级不同,就可进行比较:

a=(1,Item('foo'))
b=(5,Item('bar'))
c=(1,Item('gork'))
print('a<b: ',a<b)
print('a<c: ',a<c)
>>> 
a<b: True
Traceback (most recent call last):
 File "D:\4autotests\02script\python-cookbook\python-cookbook-master\src\1\5.implementing_a_priority_queue\example.py", line 29, in <module>
  print('a<c: ',a<c)
TypeError: unorderable types: Item() < Item()
>>>

引入额外的索引值,以(priority, index, item)的方式建立元组,就可以避免相同优先级无法比较的问题,因为没有哪两个元组会有相同的index值;

a=(1,0,Item('foo'))
b=(5,1,Item('bar'))
c=(1,2,Item('gork'))
print('a<b: ',a<b)
print('a<c: ',a<c)
>>> 
a<b: True
a<c: True
>>>

如果想将这个队列用于线程间通信,还需要增加适当的锁和信号机制。

(代码摘自《Python Cookbook》)

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
使用Python进行稳定可靠的文件操作详解
Dec 31 Python
python实现的系统实用log类实例
Jun 30 Python
Django代码性能优化与Pycharm Profile使用详解
Aug 26 Python
Python从数据库读取大量数据批量写入文件的方法
Dec 10 Python
Python Numpy 实现交换两行和两列的方法
Jun 26 Python
如何利用python给图片添加半透明水印
Sep 06 Python
Python进程间通信 multiProcessing Queue队列实现详解
Sep 23 Python
Django restframework 框架认证、权限、限流用法示例
Dec 21 Python
python定时截屏实现
Nov 02 Python
用Python提取PDF表格的方法
Apr 11 Python
python微信智能AI机器人实现多种支付方式
Apr 12 Python
Python matplotlib绘制条形统计图 处理多个实验多组观测值
Apr 21 Python
python快速建立超简单的web服务器的实现方法
Feb 17 #Python
Python cookbook(数据结构与算法)找到最大或最小的N个元素实现方法示例
Feb 13 #Python
python3学习笔记之多进程分布式小例子
Feb 13 #Python
Python cookbook(数据结构与算法)保存最后N个元素的方法
Feb 13 #Python
Python cookbook(数据结构与算法)从任意长度的可迭代对象中分解元素操作示例
Feb 13 #Python
Python cookbook(数据结构与算法)将序列分解为单独变量的方法
Feb 13 #Python
Python内置模块ConfigParser实现配置读写功能的方法
Feb 12 #Python
You might like
深入理解PHP之数组(遍历顺序)  Laruence原创
2012/06/13 PHP
深入解析PHP中的(伪)多线程与多进程
2013/07/01 PHP
浅谈PHP变量作用域以及地址引用问题
2013/12/27 PHP
PHP的Yii框架入门使用教程
2016/02/15 PHP
由浅到深了解JavaScript类
2006/09/08 Javascript
js鼠标滑过弹出层的定位IE6bug解决办法
2012/12/26 Javascript
javascript中[]和{}对象使用介绍
2013/03/20 Javascript
document.execCommand()的用法小结
2014/01/08 Javascript
jquery mobile的触控点击事件会多次触发问题的解决方法
2014/05/08 Javascript
AngularJS中update两次出现$promise属性无法识别的解决方法
2017/01/05 Javascript
canvas 绘制圆形时钟
2017/02/22 Javascript
react.js CMS 删除功能的实现方法
2017/04/17 Javascript
关于JavaScript中的this指向问题总结篇
2017/07/23 Javascript
jquery实现楼层滚动效果
2018/01/01 jQuery
在vue中,v-for的索引index在html中的使用方法
2018/03/06 Javascript
Vue.js实现表格渲染的方法
2018/09/07 Javascript
详解微信小程序开发(项目从零开始)
2019/06/06 Javascript
[05:49]DOTA2-DPC中国联赛 正赛 Elephant vs LBZS 选手采访
2021/03/11 DOTA
利用Django框架中select_related和prefetch_related函数对数据库查询优化
2015/04/01 Python
python中base64加密解密方法实例分析
2015/05/16 Python
Python yield 使用浅析
2015/05/28 Python
Python生成数字图片代码分享
2017/10/31 Python
Python利用matplotlib做图中图及次坐标轴的实例
2019/07/08 Python
python-序列解包(对可迭代元素的快速取值方法)
2019/08/24 Python
python安装virtualenv虚拟环境步骤图文详解
2019/09/18 Python
python自动点赞功能的实现思路
2020/02/26 Python
Django之腾讯云短信的实现
2020/06/12 Python
html5 application cache遇到的严重问题
2012/12/26 HTML / CSS
皇家阿尔伯特英国官方商店:Royal Albert骨瓷
2019/03/25 全球购物
最新党员的自我评价分享
2013/11/04 职场文书
简单的项目建议书模板
2014/03/12 职场文书
党的群众路线教育实践方案
2014/05/11 职场文书
酒店端午节活动方案
2014/08/26 职场文书
2014年社区综治工作总结
2014/11/17 职场文书
机动车交通事故协议书
2015/01/29 职场文书
篮球赛闭幕式主持词
2015/07/03 职场文书