zoukankan      html  css  js  c++  java
  • Python -- 堆数据结构 heapq

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

    Python -- 堆数据结构 heapq

    分类: Python 458人阅读 评论(0) 收藏 举报

    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]

    构建元素个数为 K=5 的最小堆代码实例:

    1. #!/usr/bin/env python  
    2. # -*- encoding: utf-8 -*-  
    3. # Author: kentzhan  
    4. #  
    5.   
    6. import heapq  
    7. import random  
    8.   
    9. heap = []  
    10. heapq.heapify(heap)  
    11. for i in range(15):  
    12.   item = random.randint(10100)  
    13.   print "comeing ", item,  
    14.   if len(heap) >= 5:  
    15.     top_item = heap[0# smallest in heap  
    16.     if top_item < item: # min heap  
    17.       top_item = heapq.heappop(heap)  
    18.       print "pop", top_item,  
    19.       heapq.heappush(heap, item)  
    20.       print "push", item,  
    21.   else:  
    22.     heapq.heappush(heap, item)  
    23.     print "push", item,  
    24.   pass  
    25.   print heap  
    26. pass  
    27. print heap  
    28.   
    29. print "sort"  
    30. heap.sort()  
    31.   
    32. print heap  
    结果:
  • 相关阅读:
    加密的PDF文件怎么查看
    SQL Server数据库中怎么加密数据
    虚拟磁盘也加密
    怎么用密码保护您的文件夹
    如何用cmd命令加密文件夹
    快压轻松创建加密压缩包
    GPS学习的一些链接
    【最新软件预告】邮件群发器Console版
    第六格很酷的滚动活动会员条
    邀请您加入移动开发专家联盟
  • 原文地址:https://www.cnblogs.com/lexus/p/3313101.html
Copyright © 2011-2022 走看看