zoukankan      html  css  js  c++  java
  • 查找最大或最小的 N 个元素

    demo1

    import heapq
    nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
    print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]

    输出:

    [42, 37, 23]
    [-4, 1, 2]

    demo2

    import heapq
    portfolio = [
        {'name': 'IBM', 'shares': 100, 'price': 91.1},
        {'name': 'AAPL', 'shares': 50, 'price': 543.22},
        {'name': 'FB', 'shares': 200, 'price': 21.09},
        {'name': 'HPQ', 'shares': 35, 'price': 31.75},
        {'name': 'YHOO', 'shares': 45, 'price': 16.35},
        {'name': 'ACME', 'shares': 75, 'price': 115.65}
    ]
    cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
    expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
    print(cheap,"
    ")
    print(expensive)

    输出:

    [{'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}] 
    
    [{'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'ACME', 'shares': 75, 'price': 115.65}, {'name': 'IBM', 'shares': 100, 'price': 91.1}]

    demo3

    >>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    >>> import heapq
    >>> heap = list(nums)
    >>> heapq.heapify(heap)
    >>> heap
    [-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
    >>>

    堆数据结构最重要的特征是 heap[0] 永远是最小的元素。并且剩余的元素可以很容易的通过调用 heapq.heappop() 方法得到, 该方法会先将第一个元素弹出来,然后用下一个最小的元素来取代被弹出元素(这种操作时间复杂度仅仅是 O(log N),N 是堆大小)。 比如,如果想要查找最小的 3 个元素,你可以这样做:

    >>> heapq.heappop(heap)
    -4
    >>> heapq.heappop(heap)
    1
    >>> heapq.heappop(heap)
    2

    demo4

    >>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    >>> import heapq
    >>> heap = list(nums)
    >>> heapq.heapify(heap)
    >>> heap
    [-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
    >>> heap[0]
    -4
    >>> heap[1]
    2
    >>> heapq.heappop(heap)
    -4
    >>> heap[0]
    1

    注意:一旦pop ,原heap就会发生改变。

  • 相关阅读:
    C语言指针
    Windows环境下 PHP+Apache+Mysql配置
    游戏贴图中常用术语《DC》的理解
    C# winform程序如何打包64位安装程序
    C# winform中的datagridview控件标头加入checkbox,实现全选功能。
    C# WinForm控件之Dock顺序调整
    关于struts2.0 中 struts.xml设置了struts.devMode 的值为TRUE后仍然不起作用的分析
    Java Web项目 配置 ueditor心得
    关于VS中文件属性的解释
    使用Ueditor的心得。
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10567094.html
Copyright © 2011-2022 走看看