python 堆和优先队列的使用详解


Posted in Python onMarch 05, 2019

1.heapq

python里面的堆是通过在列表中维护堆的性质实现的。这一点与C++中heap一系列的算法类似,底层是通过堆vector的维护获取堆的性质。

关于二叉树

二叉树的特点:

二叉树是一种存储数据元素的汇集数据结构。

二叉树最重要的性质就是树的高度和树中可以容纳的最大结点个数之间的关系。树的高度类似于表长,是从根结点到其他结点的最大距离。在长为n的表里只能容纳n个结点,而在高为h的二叉树中则可以容纳大约2^h个结点,这是表和树的最大不同点。

一般的元素插入,如果是按线性顺序排列的,那么操作必然需要O(n)的时间(需要对n个数据进行移位处理),要突破这个限制,必须考虑其他数据结构的组织方式。二叉树就是一种高效插入的存储方式。

堆排序利用的是完全二叉树。

python堆的部分API,其他API查阅文档python_heap_API和  heapq的源代码

import heapq
#向堆中插入元素,heapq会维护列表heap中的元素保持堆的性质
heapq.heappush(heap, item)
#heapq把列表x转换成堆
heapq.heapify(x)
#从可迭代的迭代器中返回最大的n个数,可以指定比较的key
heapq.nlargest(n, iterable[, key])
#从可迭代的迭代器中返回最小的n个数,可以指定比较的key
heapq.nsmallest(n, iterable[, key])
#从堆中删除元素,返回值是堆中最小或者最大的元素
heapq.heappop(heap)

1.1.内置类型

从上述源代码可以看出来,heapq使用的内置的小于号,或者类的__lt__比较运算来进行比较。

def heapq_int():
  heap = []
  #以堆的形式插入堆
  heapq.heappush(heap,10)
  heapq.heappush(heap,1)
  heapq.heappush(heap,10/2)
  [heapq.heappush(heap,i) for i in range(10)]
  [heapq.heappush(heap,10 - i) for i in range(10)]
  #最大的10个元素
  print heapq.nlargest(10,heap)
  #输出所有元素
  print [heapq.heappop(heap) for i in range(len(heap))]

1.2.元组类型

元素会默认调用内置比较函数cmp

def heapq_tuple():
  heap = []
  #向推中插入元组
  heapq.heappush(heap,(10,'ten'))
  heapq.heappush(heap,(1,'one'))
  heapq.heappush(heap,(10/2,'five'))
  while heap:
    print heapq.heappop(heap),
  print

1.2.类类型

类类型,使用的是小于号_lt_,当然没有重写但是有其他的比较函数例如:_le_,_gt_,_cmp_,也是会调用的,和小于号等价的都可以调用(测试了gt),具体的这些操作之间的关系我也没有研究过。如果类里面没有重写_lt_,会调用其他的比较操作符,从源代码可以看出来,如果没有_lt_,那么会调用_ge_函数。

所以可以重写上述的那些函数:

class Skill(object):
  def __init__(self,priority,description):
    self.priority = priority
    self.description = description
  def __lt__(self,other):#operator < 
    return self.priority < other.priority
  def __ge__(self,other):#oprator >=
    return self.priority >= other.priority
  def __le__(self,other):#oprator <=
    return self.priority <= other.priority
  def __cmp__(self,other):
    #call global(builtin) function cmp for int
    return cmp(self.priority,other.priority)
  def __str__(self):
    return '(' + str(self.priority)+',\'' + self.description + '\')'

def heapq_class():
  heap = []
  heapq.heappush(heap,Skill(5,'proficient'))
  heapq.heappush(heap,Skill(10,'expert'))
  heapq.heappush(heap,Skill(1,'novice'))
  while heap:
    print heapq.heappop(heap),
  print

所以如果要用到自己定义的类型,可以重写上述函数,就可以使用heapq函数了。

2.PriorityQueue

PriorityQueue的python源代码PriorityQueue 

从源代码可以看出来,PriorityQueue使用的就是heapq来实现的,所以可以认为两者算法本质上是一样的。当然PriorityQueue考虑到了线程安全的问题。

下面给出PriorityQueue的部分API和使用方法。

参考Queue

#向队列中添加元素
Queue.put(item[, block[, timeout]])
#从队列中获取元素
Queue.get([block[, timeout]])
#队列判空
Queue.empty()
#队列大小
Queue.qsize()

2.1.内置类型

直接调用内置函数cmp进行比较

try:
  import Queue as Q #python version < 3.0
except ImportError:
  import queue as Q #python3.*
def PriorityQueue_int():
  que = Q.PriorityQueue()
  que.put(10)
  que.put(1)
  que.put(5)
  while not que.empty():
    print que.get(),
  print

2.2.元组类型

def PriorityQueue_tuple():
  que = Q.PriorityQueue()
  que.put((10,'ten'))
  que.put((1,'one'))
  que.put((10/2,'five'))
  while not que.empty():
    print que.get(),
  print

2.2.自定义类型

class Skill(object):
  def __init__(self,priority,description):
    self.priority = priority
    self.description = description
  #下面两个方法重写一个就可以了
  def __lt__(self,other):#operator < 
    return self.priority < other.priority
  def __cmp__(self,other):
    #call global(builtin) function cmp for int
    return cmp(self.priority,other.priority)
  def __str__(self):
    return '(' + str(self.priority)+',\'' + self.description + '\')'

def PriorityQueue_class():
  que = Q.PriorityQueue()
  skill5 = Skill(5,'proficient')
  skill6 = Skill(6,'proficient6')
  que.put(skill6)
  que.put(Skill(5,'proficient'))
  que.put(Skill(10,'expert'))
  que.put(Skill(1,'novice'))
  while not que.empty():
    print que.get(),
  print

其他的一些方法的使用还是需要参考给出的文档的。

最后一点,让我比较奇怪的是(可能我并没有找到),没有提供像排序函数那样,指定比较方法函数,这点和c++有点区别。

这篇文档参考:参考文档

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python修改操作系统时间的方法
May 18 Python
python检查指定文件是否存在的方法
Jul 06 Python
python微信跳一跳系列之色块轮廓定位棋盘
Feb 26 Python
Windows下安装Django框架的方法简明教程
Mar 28 Python
python按行读取文件,去掉每行的换行符\n的实例
Apr 19 Python
使用Python实现微信提醒备忘录功能
Dec 04 Python
基于python if 判断选择结构的实例详解
May 06 Python
Python实现通过解析域名获取ip地址的方法分析
May 17 Python
Python3内置模块pprint让打印比print更美观详解
Jun 02 Python
python中pip的使用和修改下载源的方法
Jul 08 Python
numpy np.newaxis 的实用分享
Nov 30 Python
Python实现简单的俄罗斯方块游戏
Sep 25 Python
Python两个字典键同值相加的几种方法
Mar 05 #Python
详解python算法之冒泡排序
Mar 05 #Python
Python字符串通过'+'和join函数拼接新字符串的性能测试比较
Mar 05 #Python
Python实现KNN(K-近邻)算法的示例代码
Mar 05 #Python
Python按钮的响应事件详解
Mar 04 #Python
Python中三元表达式的几种写法介绍
Mar 04 #Python
Python生成器的使用方法和示例代码
Mar 04 #Python
You might like
php实现的MySQL通用查询程序
2007/03/11 PHP
PHP中如何实现常用邮箱的基本判断
2014/01/07 PHP
jQuery初学:find()方法及children方法的区别分析
2011/01/31 Javascript
仿百度输入框智能提示的js代码
2013/08/22 Javascript
使用变量动态设置js的属性名
2014/10/19 Javascript
什么是 AngularJS?AngularJS简介
2014/12/06 Javascript
JavaScript+canvas实现七色板效果实例
2016/02/18 Javascript
jQuery实现的placeholder效果完整实例
2016/08/02 Javascript
jQuery继承extend用法详解
2016/10/10 Javascript
如何使用jquery实现文字上下滚动效果
2016/10/12 Javascript
Vue.js实现表格动态增加删除的方法(附源码下载)
2017/01/20 Javascript
js实现文字选中分享功能
2017/01/25 Javascript
jQuery表格的维护和删除操作
2017/02/03 Javascript
使用jQuery操作DOM的方法小结
2017/02/27 Javascript
Vue 2.5 Level E 发布了: 新功能特性一览
2017/10/24 Javascript
自定义Vue组件打包、发布到npm及使用教程
2019/05/22 Javascript
element跨分页操作选择详解
2020/06/29 Javascript
[01:02:30]Mineski vs Secret 2019国际邀请赛淘汰赛 败者组 BO3 第三场 8.22
2019/09/05 DOTA
Python使用百度API上传文件到百度网盘代码分享
2014/11/08 Python
Python抓取电影天堂电影信息的代码
2016/04/07 Python
python Matplotlib画图之调整字体大小的示例
2017/11/20 Python
Python2.7+pytesser实现简单验证码的识别方法
2017/12/29 Python
python正则表达式爬取猫眼电影top100
2018/02/24 Python
浅析Python 中几种字符串格式化方法及其比较
2019/07/02 Python
将tensorflow模型打包成PB文件及PB文件读取方式
2020/01/23 Python
pyinstaller打包单文件时--uac-admin选项不起作用怎么办
2020/04/15 Python
python删除文件、清空目录的实现方法
2020/09/23 Python
python实现录制全屏和选择区域录屏功能
2021/02/05 Python
中国旅游网站:同程旅游
2016/09/11 全球购物
商务日语毕业生自荐信
2013/11/23 职场文书
采购部部长岗位职责
2014/02/06 职场文书
房产继承公证书
2014/04/09 职场文书
高三数学教学反思
2016/02/18 职场文书
端午节将至,用Python爬取粽子数据并可视化,看看网友喜欢哪种粽子吧!
2021/06/11 Python
将MySQL的表数据全量导入clichhouse库中
2022/03/21 MySQL
Win11 Beta 22621.601 和 22622.601今日发布 KB5017384修复内容汇总
2022/09/23 数码科技