Python有一个内置的模块,heapq标准的封装了最小堆的算法实现。下面看两个不错的应用。

小顶堆(求TopK大)

话说需求是这样的: 定长的序列,求出TopK大的数据。

import heapq
import random

class TopkHeap(object):
    def __init__(self, k):
        self.k = k
        self.data = []

    def Push(self, elem):
        if len(self.data) < self.k:
            heapq.heappush(self.data, elem)
        else:
            topk_small = self.data[0]
            if elem > topk_small:
                heapq.heapreplace(self.data, elem)

    def TopK(self):
        return [x for x in reversed([heapq.heappop(self.data) for x in xrange(len(self.data))])]

if __name__ == "__main__":
    print "Hello"
    list_rand = random.sample(xrange(1000000), 100)
    th = TopkHeap(3)
    for i in list_rand:
        th.Push(i)
    print th.TopK()
    print sorted(list_rand, reverse=True)[0:3]

大顶堆(求BtmK小)

这次的需求变得更加的困难了:给出N长的序列,求出BtmK小的元素,即使用大顶堆。

算法实现的核心思路是:将push(e)改为push(-e)、pop(e)改为-pop(e)。

class BtmkHeap(object):
    def __init__(self, k):
        self.k = k
        self.data = []

    def Push(self, elem):
        # Reverse elem to convert to max-heap
        elem = -elem
        # Using heap algorighem
        if len(self.data) < self.k:
            heapq.heappush(self.data, elem)
        else:
            topk_small = self.data[0]
            if elem > topk_small:
                heapq.heapreplace(self.data, elem)

    def BtmK(self):
        return sorted([-x for x in self.data])

题外话

Python 妙用heapq的更多相关文章

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

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

  2. Python系列之heapq内置模块

    heapq 是 python 的内置模块,源码位于 Lib/heapq.py ,该模块提供了基于堆的优先排序算法. 堆的逻辑结构就是完全二叉树,并且二叉树中父节点的值小于等于该节点的所有子节点的值.这 ...

  3. 『Python CoolBook:heapq』数据结构和算法_heapq堆队列算法&容器排序

    一.heapq堆队列算法模块 本模块实现了堆队列算法,也叫作优先级队列算法.堆队列是一棵二叉树,并且拥有这样特点,它的父节点的值小于等于任何它的子节点的值. 本模块实际上实现了一系列操作容器的方法,使 ...

  4. python collection 和 heapq 模块使用说明

    一 :集合库collection python 拥有一些内置的数据类型,collections模块提供啦几个额外的数据类型: 1,namedtuple   生成可以使用名字来访问元素内容的tuple子 ...

  5. python中使用heapq查看最大与最小的N个元素列表

    怎么从一个集合中获取最大或最小的N个元素列表? heapq模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题. In [39]: import heapq In [ ...

  6. python之使用heapq()函数计算列表中数值大小

    # heapq函数:计算列表最大几个值和最小几个值 # 语法:heapq.nlargest(n, list,[key]) # n表示最大或最小的几个: list为分析的对象: key为排序关键字,非必 ...

  7. python 排序模块 ———— heapq(学习笔记)

    from heapq import * def heasort(initi):# 排序 h=[] for value in initi: heappush(h,value)#将每一个item进入hea ...

  8. Python妙用re.sub分析正则表达式匹配过程

    声明:本文所使用方法为老猿自行研究并编码,相关代码版权为老猿所有,禁止转载文章,代码禁止用于商业用途! 在<第11.23节 Python 中re模块的搜索替换功能:sub及subn函数>介 ...

  9. python学习笔记之heapq内置模块

    heapq内置模块位于./Anaconda3/Lib/heapq.py,提供基于堆的优先排序算法 堆的逻辑结构就是完全二叉树,并且二叉树中父节点的值小于等于该节点的所有子节点的值.这种实现可以使用 h ...

随机推荐

  1. [ZooKeeper] 1 基本概念

    ZooKeeper: A Distributed Coordination Service for Distributed Applications ZooKeeper is a distribute ...

  2. angualar2——八大组成

    Angular2 模块 理解: Angular 应用是模块化的,并且 Angular 有自己的模块系统,它被称为 Angular 模块或 NgModules. 组件 组件是一个项目主干,一个模块由多个 ...

  3. [LeetCode] Partition to K Equal Sum Subsets 分割K个等和的子集

    Given an array of integers nums and a positive integer k, find whether it's possible to divide this ...

  4. [LeetCode] Top K Frequent Words 前K个高频词

    Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted b ...

  5. json pickle ;shelve

    import json dic={'name':'alex'} """ f=open("new_hello","w") # dic ...

  6. 以 Angular 的姿势打开 Font-Awesome

    环境 Angular: v5.2.9 Font-Awesome: v5.0.10 angular-fontawesome: v0.1.0-9 无须再用传统的 Web Font 方式 以前习惯于 Fon ...

  7. [SDOI 2011]染色

    Description 题库链接 给定一棵有 \(n\) 个节点的无根树和 \(m\) 个操作,操作有 \(2\) 类: 将节点 \(a\) 到节点 \(b\) 路径上所有点都染成颜色 \(c\) : ...

  8. [HOJ2634] How to earn more 最大权闭合子图

    Xiao Ming is an expert in computer science and technology, so he can get a lot of projects every mon ...

  9. ●POJ 1269 Intersecting Lines

    题链: http://poj.org/problem?id=1269 题解: 计算几何,直线交点 模板题,试了一下直线的向量参数方程求交点的方法. (方法详见<算法竞赛入门经典——训练指南> ...

  10. [BZOJ]1079 着色方案(SCOI2008)

    相邻色块不同的着色方案,似乎这道题已经见过3个版本了. Description 有n个木块排成一行,从左到右依次编号为1~n.你有k种颜色的油漆,其中第i种颜色的油漆足够涂ci个木块.所有油漆刚好足够 ...