Python heapq使用详解及实例代码

yipeiwu_com6年前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解决计数原理问题的方法

用Python解决计数原理问题的方法

前几天遇到这样一道数学题: 用四种不同颜色给三棱柱六个顶点涂色,要求每个点涂一种颜色,且每条棱的两个端点涂不同颜色,则不同的涂色方法有多少种? 当我看完题目后,顿时不知所措。于是我拿起...

python生成IP段的方法

python生成IP段的方法

本文实例讲述了python生成IP段的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/local/bin/python #-*- coding: UTF-8 -*- #...

快速入手Python字符编码

前言 对于很多接触Python的人而言,字符的处理和语言整体的温顺可靠相比显得格外桀骜不驯难以驾驭。 文章针对Python 2.7,主要因为3对的编码已经有了很大的改善并且实际原理一样,...

对numpy和pandas中数组的合并和拆分详解

合并 numpy中 numpy中可以通过concatenate,指定参数axis=0 或者 axis=1,在纵轴和横轴上合并两个数组。 import numpy as np impo...

详解Python中的Cookie模块使用

详解Python中的Cookie模块使用

最近在用GAE开发自己的博客程序。虽然GAE的API没有显式的提供操作Cookie的方法,但他现有的架构,使我们有足够的自由来操作Cookie。 Cookie 模块,顾名思义,就是用来操...