• heapq堆队列


    # 堆队列
    import heapq
    
    # 怎样从一个集合中获得最大或者最小的 N 个元素列表?
    nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    # 最大的3个
    print(heapq.nlargest(3, nums))
    # 最小的3个
    print(heapq.nsmallest(3, nums))
    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}
    ]
    # key为比较值 key=func,这里用lambda
    # 底层调用max(iterable, *[, default=obj, key=func])
    print(heapq.nlargest(3, portfolio, key=lambda i: i['shares']))
    print(heapq.nsmallest(3, portfolio, lambda i: i['price']))
    # 堆化
    heapq.heapify(nums)
    print(nums)  # [-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
    print(heapq.heappop(nums))  # -4
    print(heapq.heappop(nums))  # 1
    print(heapq.heappop(nums))  # 2
    
    
    # 简单的优先级队列
    class PriorityQueue:
        def __init__(self):
            self._queue = []
            self._index = 0
    
        def push(self, item, priority):
            heapq.heappush(self._queue, (-priority, self._index, item))  # 最大的会成为最小的排到最前面,push是按照小->大,相同的比较_index
            self._index += 1
    
        def pop(self):
            return heapq.heappop(self._queue)[-1]
    
    
    class Item:
        def __init__(self, name):
            self.name = name
    
        def __repr__(self):
            return 'Item({!r})'.format(self.name)
    
    
    print('='*20)
    q = PriorityQueue()
    q.push(Item('foo'), 1)
    q.push(Item('bar'), 5)
    q.push(Item('spam'), 4)
    q.push(Item('grok'), 1)
    q.push(Item('sam'), -1)
    print(q.pop())
    print(q.pop())
    print(q.pop())
    print(q.pop())
    print(q.pop())
    
    
  • 相关阅读:
    NOIP200801 ISBN号码
    NOIP200902分数线划定
    NOIP200901多项式输出
    NOIP200603 Jam的计数法
    HDNOIP201102读数
    Modular Inverse(扩展欧几里得)
    青蛙的约会(扩展欧几里得)
    A Famous City(单调栈)
    Triangles
    2971: 魔族密码 (trie树)
  • 原文地址:https://www.cnblogs.com/fly-book/p/13385913.html
Copyright © 2020-2023  润新知