python中如何使用堆和优先队列-创新互联

今天就跟大家聊聊有关python中如何使用堆和优先队列,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

成都创新互联公司服务项目包括惠安网站建设、惠安网站制作、惠安网页制作以及惠安网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,惠安网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到惠安省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!

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

看完上述内容,你们对python中如何使用堆和优先队列有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联成都网站设计公司行业资讯频道,感谢大家的支持。

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


分享标题:python中如何使用堆和优先队列-创新互联
网站地址:http://myzitong.com/article/ceeeej.html