# Python -- 堆数据结构 heapq

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]

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Author: kentzhan
#

import heapq
import random

heap = []
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 heap
if top_item < item: # min heap
top_item = heapq.heappop(heap)
print "pop", top_item,
heapq.heappush(heap, item)
print "push", item,
else:
heapq.heappush(heap, item)
print "push", item,
pass
print heap
pass
print heap

print "sort"
heap.sort()

print heap

• 本文已收录于以下专栏：

## Python 技巧（二） 最小堆实现以及维护一个大小为100的最小堆

#!/usr/bin/env python #coding:utf-8 __author__ = 'sws'class MinHeap: ''' 最小堆 ''' ...
• shengweisong
• 2017年03月02日 23:43
• 543

## 最小堆 构建、插入、删除的过程图解

1.简介        最小堆是一棵完全二叉树，非叶子结点的值不大于左孩子和右孩子的值。本文以图解的方式，说明 最小堆的构建、插入、删除的过程。搞懂最小堆的相应知识后，最大堆与此类似。 2.最小...
• hrn1216
• 2016年05月21日 00:47
• 33332

## 二叉堆 最小堆 Python 实现

• 2014年03月01日 19:58
• 3KB
• 下载

## 浅析Python heapq模块 堆数据结构

• minxihou
• 2016年07月08日 01:42
• 11867

## 5.4 heapq--堆队列算法

• caimouse
• 2016年01月16日 18:49
• 3059

## 用Python实现八大排序算法--堆排序

• chibangyuxun
• 2016年11月03日 09:30
• 1328

## 利用Python实现堆排序

• minxihou
• 2016年07月07日 11:41
• 4832

## python 堆和优先队列的使用

1.heapqpython里面的堆是通过在列表中维护堆的性质实现的。这一点与C++中heap一系列的算法类似，底层是通过堆vector的维护获取堆的性质。 python堆的部分API，其他API查阅...
• liu2012huan
• 2016年11月21日 21:39
• 6398

## python使用heapq实现小顶堆（TopK大）/大顶堆（BtmK小）

• tanghaiyu777
• 2017年02月16日 19:16
• 981

## Python——heap

• u010480899
• 2016年10月19日 22:19
• 1640

举报原因： 您举报文章：Python -- 堆数据结构 heapq 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)