Python heapq使用详解及实例代码

yipeiwu_com7年前Python基础

 Python heapq 详解

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中super()函数简介及用法分享

首先看一下super()函数的定义: super([type [,object-or-type]]) Return a **proxy object** that delegates m...

详解opencv Python特征检测及K-最近邻匹配

详解opencv Python特征检测及K-最近邻匹配

鉴于即将启程旅行,先上传篇简单的图像检索介绍,与各位一起学习opencv的同学共勉 一.特征检测 图片的特征主要分为角点,斑点,边,脊向等,都是常用特征检测算法所检测到的图像特征· 1....

更换Django默认的模板引擎为jinja2的实现方法

本机环境 操作系统:fedora24 python版本:3.5 Django版本:1.11.1 jinja2版本:2.9.6 为何要更换 DTL 先来谈谈Django的模板引擎,找了下,...

基于pandas将类别属性转化为数值属性的方法

基于pandas将类别属性转化为数值属性的方法

离散特征的编码分为两种情况: 1、离散特征的取值之间没有大小的意义,比如color:[red,blue],那么就使用one-hot编码 2、离散特征的取值有大小的意义,比如size:[...

Python从文件中读取指定的行以及在文件指定位置写入

Python从文件中读取指定的行 如果想根据给出的行号, 从文本文件中读取一行数据,  Python标准库linecache模块非常适合这个任务: 测试文件内容 : This...