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简单实现旋转图片的方法

本文实例讲述了python简单实现旋转图片的方法。分享给大家供大家参考。具体实现方法如下: # rotate an image counter-clockwise using the...

Python中operator模块的操作符使用示例总结

operator模块是python中内置的操作符函数接口,它定义了一些算术和比较内置操作的函数。operator模块是用c实现的,所以执行速度比python代码快。 逻辑操作 fr...

Python实现判断字符串中包含某个字符的判断函数示例

Python实现判断字符串中包含某个字符的判断函数示例

本文实例讲述了Python实现判断字符串中包含某个字符的判断函数。分享给大家供大家参考,具体如下: #coding=utf8 #参数包含两个: #containVar:查找包含的字符...

Python使用matplotlib绘制正弦和余弦曲线的方法示例

Python使用matplotlib绘制正弦和余弦曲线的方法示例

本文实例讲述了Python使用matplotlib绘制正弦和余弦曲线的方法。分享给大家供大家参考,具体如下: 一 介绍 关键词:绘图库 官网:http://matplotlib.org/...

python使用socket进行简单网络连接的方法

本文实例讲述了python使用socket进行简单网络连接的方法。分享给大家供大家参考。具体如下: import socket print "Creating socket...",...