Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET

分类: Python 2012-09-17 14:56 458人阅读 评论(0) 收藏 举报

import heapq

help(heapq)

heapq 是一个最小堆,堆顶元素 a[0] 永远是最小的. 和 Java 中的优先队列类似.

-------------------------------------------------

Help on module heapq:

NAME
    heapq - Heap queue algorithm (a.k.a. priority queue).

FILE
    /usr/lib64/python2.4/heapq.py

DESCRIPTION
    Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
    all k, counting elements from 0.  For the sake of comparison,
    non-existing elements are considered to be infinite.  The interesting
    property of a heap is that a[0] is always its smallest element.
    
    Usage:
    
    heap = []            # creates an empty heap
    heappush(heap, item) # pushes a new item on the heap
    item = heappop(heap) # pops the smallest item from the heap
    item = heap[0]       # smallest item on the heap without popping it
    heapify(x)           # transforms list into a heap, in-place, in linear time
    item = heapreplace(heap, item) # pops and returns smallest item, and adds
                                   # new item; the heap size is unchanged
    
    Our API differs from textbook heap algorithms as follows:
    
    - We use 0-based indexing.  This makes the relationship between the
      index for a node and the indexes for its children slightly less
      obvious, but is more suitable since Python uses 0-based indexing.
    
    - Our heappop() method returns the smallest item, not the largest.
    
    These two make it possible to view the heap as a regular Python list
    without surprises: heap[0] is the smallest item, and heap.sort()
    maintains the heap invariant!

FUNCTIONS
    heapify(...)
        Transform list into a heap, in-place, in O(len(heap)) time.
    
    heappop(...)
        Pop the smallest item off the heap, maintaining the heap invariant.
    
    heappush(...)
        Push item onto heap, maintaining the heap invariant.
    
    heapreplace(...)
        Pop and return the current smallest value, and add the new item.
        
        This is more efficient than heappop() followed by heappush(), and can be
        more appropriate when using a fixed-size heap.  Note that the value
        returned may be larger than item!  That constrains reasonable uses of
        this routine unless written as part of a conditional replacement:
        
                if item > heap[0]:
                    item = heapreplace(heap, item)
    
    nlargest(...)
        Find the n largest elements in a dataset.
        
        Equivalent to:  sorted(iterable, reverse=True)[:n]
    
    nsmallest(...)
        Find the n smallest elements in a dataset.
        

Equivalent to:  sorted(iterable)[:n]

构建元素个数为 K=5 的最小堆代码实例:

  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. # Author: kentzhan
  4. #
  5. import heapq
  6. import random
  7. heap = []
  8. heapq.heapify(heap)
  9. for i in range(15):
  10. item = random.randint(10, 100)
  11. print "comeing ", item,
  12. if len(heap) >= 5:
  13. top_item = heap[0] # smallest in heap
  14. if top_item < item: # min heap
  15. top_item = heapq.heappop(heap)
  16. print "pop", top_item,
  17. heapq.heappush(heap, item)
  18. print "push", item,
  19. else:
  20. heapq.heappush(heap, item)
  21. print "push", item,
  22. pass
  23. print heap
  24. pass
  25. print heap
  26. print "sort"
  27. heap.sort()
  28. print heap
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Author: kentzhan
# import heapq
import random heap = []
heapq.heapify(heap)
for i in range(15):
item = random.randint(10, 100)
print "comeing ", item,
if len(heap) >= 5:
top_item = heap[0] # smallest in heap
if top_item < item: # min heap
top_item = heapq.heappop(heap)
print "pop", top_item,
heapq.heappush(heap, item)
print "push", item,
else:
heapq.heappush(heap, item)
print "push", item,
pass
print heap
pass
print heap print "sort"
heap.sort() print heap

结果:

Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET的更多相关文章

  1. 解决基于BAE python+bottle开发上的一系列问题 - artwebs - 博客频道 - CSDN.NET

    解决基于BAE python+bottle开发上的一系列问题 - artwebs - 博客频道 - CSDN.NET 解决基于BAE python+bottle开发上的一系列问题 分类: python ...

  2. python实现的文本编辑器 - Skycrab - 博客频道 - CSDN.NET

    Download Qt, the cross-platform application framework | Qt Project Qt 5.2.1 for Windows 64-bit (VS 2 ...

  3. python random模块 - 小驹的专栏 - 博客频道 - CSDN.NET

    python random模块 - 小驹的专栏 - 博客频道 - CSDN.NET python random模块 分类: python 2011-11-15 15:31 6037人阅读 评论(2) ...

  4. 堆数据结构(heapq)简单应用

    ## 堆数据结构(heapq)简单应用 # 堆数据结构 heapq # 常用方法:nlargest(),nsmallest(),heapify(),heappop() # 如果需要的个数较小,使用nl ...

  5. Python 爬取CSDN博客频道

    初次接触python,写的很简单,开发工具PyCharm,python 3.4很方便 python 部分模块安装时需要其他的附属模块之类的,可以先 pip install wheel 然后可以直接下载 ...

  6. python实现自动发送微博,当自己写博客时同步上去。

    一.需求: 自己在github上搭建一个基于Jekyll的博客(http://beginman.cn/),每次写完博客后就要push上去,博客写的再好,基本上没人访问,为了增加访问量,就想利用起来微博 ...

  7. Python爬虫学习之正则表达式爬取个人博客

    实例需求:运用python语言爬取http://www.eastmountyxz.com/个人博客的基本信息,包括网页标题,网页所有图片的url,网页文章的url.标题以及摘要. 实例环境:pytho ...

  8. python有哪些好的学习资料或者博客?

    推荐Full Stack Python 有各种python资源汇总,从基础入门到各种框架web应用开发和部署,再到高级的ORM.Docker都有.以下是Full Stack Python 上总结的一些 ...

  9. Python Web开发:Django+BootStrap实现简单的博客项目

    创建blog的项目结构 关于如何创建一个Django项目,请查看[Python Web开发:使用Django框架创建HolleWorld项目] 创建blog的数据模型 创建一个文章类 所有开发都是数据 ...

随机推荐

  1. Swift 与 Objective-C混合编程

    在Swift项目中想要同一时候加入Objective-C的库支持或者须要同一时候用Objective-C编程 在加入新的文件时选择Objective-C系统就会自己主动生成一个xx-Bridging- ...

  2. 基于visual Studio2013解决C语言竞赛题之1033数字交换

          题目 解决代码及点评 /* 功能:将一个一维数组中的偶数依次交换.例如有8个元素, 若其中第1.4.5三元素是偶数时应按下图交换. 例子: a[]={2,3,1,6 ...

  3. 遍历关联数组 index by varchar2

    --字符串序列要这样 declare     type t   is table of number(3) index by varchar2(3);    hash_t t;      l_row ...

  4. hdoj 1286 找新朋友 【数论之欧拉函数】

    找新朋友 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submi ...

  5. URAL 1018 (金典树形DP)

    连接:1018. Binary Apple Tree Time limit: 1.0 second Memory limit: 64 MB Let's imagine how apple tree l ...

  6. post 请求参数

    perl代码: my $login_url='http://192.168.1.1/getpage.gch?pid=1001&logout=1'; my $res = $ua->post ...

  7. 基于visual Studio2013解决C语言竞赛题之1077大数相加

        题目 解决代码及点评 /************************************************************************/ /* ...

  8. Eclipse完美汉化教程

    首先我们打开http://www.eclipse.org/babel/downloads.php下载语言包. 方法一:可以复制图片里的地址通过Eclipse下载,Help→Install New So ...

  9. 纯win32实现PNG图片透明窗体

    #include <windows.h> #include <gdiplus.h> /*  GDI+ startup token */ ULONG_PTR gdiplusSta ...

  10. 用DELPHI的RTTI实现对象的XML持久化

    去年我花了很多时间尝试用DELPHI进行基于XML的WEB应用开发.起初的设想是很美好的,但结果做出来的东西很简陋.一部分原因就在于XML到Object之间的数据绑定实现太麻烦(另一部分是因为对XSL ...