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. Bar Codes

    http://acm.hust.edu.cn/vjudge/contest/view.action?cid=31329#problem/N #include<map> #include&l ...

  2. Atitit.Gui控件and面板----web server区----- web服务器监控面板and控制台条目

    Atitit.Gui控件and面板----web server区----- web服务器监控面板and控制台条目 1. Resin4.0.22 1 2. 查看http连接数::Summary>& ...

  3. 【解决方法】System.IO.FileNotFoundException

    错误日志 See the end of this message for details on invoking just-in-time (JIT) debugging instead of thi ...

  4. Ajax - 手册

    一.Ajax概述:    1.Ajax(Asynchronous JavaScript and XML):异步的JavaScript和XML    2.Ajax不是某种语言,而是在现实网页的时候一种局 ...

  5. WCF消息之XmlDictionaryWriter

    原文:WCF消息之XmlDictionaryWriter XmlDictionaryWriter,是一个抽象类,从该类中派生了WCF,以便执行序列化和反序列化. 它有4种格式书写器: CreateBi ...

  6. 第13章、布局Layouts之RelativeLayout相对布局(从零開始学Android)

    RelativeLayout相对布局 RelativeLayout是一种相对布局,控件的位置是依照相对位置来计算的,后一个控件在什么位置依赖于前一个控件的基本位置,是布局最经常使用,也是最灵活的一种布 ...

  7. JDK 安装以及环境变量的配置(Windows)

    首先下载对应版本的jdk ,然后安装,这里使用的是jdk 1.7的安装的 这个时候,JDK 已经安装完成,打开cmd 输入 java -version 就可以查看到,当前JDK 的版本如图 JDK 安 ...

  8. 透神器ngrok

    内网穿透神器ngrok 相信做Web开发的同学们,经常会遇到需要将本地部署的Web应用能够让公网环境直接访问到的情况,例如微信应用调试.支付宝接口调试等.这个时候,一个叫ngrok的神器可能会帮到你, ...

  9. 博弈论之Nim

    博弈论(一):Nim游戏 重点结论:对于一个Nim游戏的局面(a1,a2,...,an),它是P-position当且仅当a1^a2^...^an=0,其中^表示位异或(xor)运算. Nim游戏是博 ...

  10. win 8.1 安装 SQL server 遇到的各种问题

    企业版 SQL Server ed2k://|file|cn_sql_server_2012_enterprise_edition_x86_x64_dvd_813295.iso|5054384128| ...