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

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

Python -- 堆数据结构 heapq

分类: Python 2012-09-17 14:56 458人阅读 评论(0) 收藏 举报
python 数据结构 arrays algorithm list encoding

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 的最小堆代码实例:

[python] view plain copy print ?
  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 randomheap = []
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 heapif top_item < item: # min heaptop_item = heapq.heappop(heap)print "pop", top_item,heapq.heappush(heap, item)print "push", item,else:heapq.heappush(heap, item)print "push", item,passprint heap
pass
print heapprint "sort"
heap.sort()print heap

结果:

posted on 2013-09-10 19:43  lexus 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lexus/p/3313101.html

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

  1. 常用排序算法的c++实现(冒泡,选择,插入,堆,shell,快速,归并 )与sort()对比 - coder_xia的专栏 - 博客频道 - CSDN.NET...

    常用排序算法的c++实现(冒泡,选择,插入,堆,shell,快速,归并 )与sort()对比 - coder_xia的专栏 - 博客频道 - CSDN.NET 常用排序算法的c++实现(冒泡,选择,插 ...

  2. Python语法解析器PLY——lex and yacc in Python - 娄振林专栏 - 博客频道 - CSDN.NET

    Python语法解析器PLY--lex and yacc in Python - 娄振林专栏 - 博客频道 - CSDN.NET Python语法解析器PLY--lex and yacc in Pyt ...

  3. python爬虫入门教程-Python爬虫入门教程——爬取自己的博客园博客

    互联网时代里,网络爬虫是一种高效地信息采集利器,可以快速准确地获取网上的各种数据资源.本文使用Python库requests.Beautiful Soup爬取博客园博客的相关信息,利用txt文件转存. ...

  4. python爬虫教程-Python爬虫入门教程——爬取自己的博客园博客

    互联网时代里,网络爬虫是一种高效地信息采集利器,可以快速准确地获取网上的各种数据资源.本文使用Python库requests.Beautiful Soup爬取博客园博客的相关信息,利用txt文件转存. ...

  5. python处理gzip压缩的http数据 - XII - 博客大巴

    python处理gzip压缩的http数据 - XII - 博客大巴 python处理gzip压缩的http数据 - XII - 博客大巴 python处理gzip压缩的http数据 - [pytho ...

  6. 【Python开发】Flask开发实战:个人博客(三)

    Flask开发实战:个人博客(三) 在[Python开发]Flask开发实战:个人博客(一) 中,我们已经完成了 数据库设计.数据准备.模板架构.表单设计.视图函数设计.电子邮件支持 等总体设计的内容 ...

  7. python 数据分析 百度网盘_[百度网盘]利用Python进行数据分析(Python For Data Analysis中文版).pdf - Jan-My31的博客 - 磁力点点...

    利用Python进行数据分析(Python For Data Analysis中文版).pdf - Jan-My31的博客 2018-5-27 · 链接:https://pan.baidu.com/s ...

  8. python之syslog学习 - 坏男孩 - 51CTO技术博客

    python之syslog学习 - 坏男孩 - 51CTO技术博客 python之syslog学习 - 坏男孩 - 51CTO技术博客 python之syslog学习 2010-04-22 17:47 ...

  9. 算法java语言描述_java语言描述数据结构与算法崔笑颜的博客

    java语言描述数据结构与算法崔笑颜的博客 冒泡排序 插入排序 选择排序 希尔排序 快速排序 归并排序 二分查找package com.demo.test; import java.util.Arra ...

最新文章

  1. vs2003复制一个web窗体,没有更改指向同一个cs 文件,引发大问题
  2. 12月3号条件控制语句和循环语句
  3. 探讨ASP.NET AJAX客户端开发技术
  4. 深入剖析HADOOP程序日志
  5. OpenGL GLFX开放GL效果库
  6. Python基础02-序列及通用操作
  7. 使用input type=file 上传文件时需注意
  8. 五个 .NET 性能小贴士
  9. querybuilder 排序_elasticsearch的匹配与排序问题
  10. 合并有序数组java
  11. 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。
  12. android系统签名一样不,解决Android应用签名和系统不一致的问题
  13. 华硕aura完全卸载_闲谈:记一次华硕电脑维修。
  14. ubuntu20.04下QT安装
  15. 我在Facebook干不下去的10个理由
  16. 批量追踪中通快运物流,并将信息导出EXCEL表格
  17. 你和csdn是什么关系
  18. python 角度传感器模拟_Arduino300度模拟旋转角度传感器
  19. 励志!从职高到杭电、浙大、MIT计算机博士!
  20. Fabric 1.0源代码分析(23)LevelDB(KV数据库)

热门文章

  1. 2021年全球化妆品阴离子表面活性剂行业调研及趋势分析报告
  2. FC炸弹人 java源码下载
  3. 火爆!联想Z5首售15分钟全网告罄力夺京东单品榜冠军
  4. Java:每日获取稳定可用免费代理ip(仅供日常使用,请勿用作他途)
  5. 无线蓝牙耳机那个品牌比较好?试试这五款比较实用的吧
  6. 【持续更新】Leetcode SQL题目全解析(附建表sql)
  7. 芯片如何储存信息_手机上的你以为信息删了就彻底删除了?事情没那么简单
  8. matlab水汽计算公式,[转载]matlab 解方程组
  9. 地理坐标xy表示什么_地理坐标怎么写 书写格式及方法
  10. 【已解决】surface 电池不好充电显示“未连接”,将充电的接口换个方向就解决了