算法-heapq模块优先队列
heapq模块, 优先队列,小顶堆,最少值放在顶部,值越小,优先级越高
heapq.heappop(heap) 从堆中弹出最小的元素,并重新调整
heapq.heappush(heap, item)新增元素添加到堆中,不会调整
heapq.heapify(x) 在线性时间内将列表x就地转换为堆
heapq.nlargest(n, iterable[, key]) 返回一个包含n个最大元素的列表,iterable是一个可迭代对象
heapq.nsmallest(n, iterable[, key])返回n个最小元素的列表
heapq.heapreplace(heap, item) 从堆中弹出并返回最小的项,并推入新项。堆大小不变。如果堆为空,则会引发IndexError
对于较小的n值执行得最好。对于较大的n值,使用sorted()函数效率更高。此外,当n==1时,使用内置的min()和max()函数效率更高。
>>> from heapq import heappush, heappop >>> heap = [] >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] >>> for item in data: ... heappush(heap, item) ... >>> ordered = [] >>> while heap: ... ordered.append(heappop(heap)) ... >>> ordered [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> data.sort() >>> data == ordered True >>> heap = [] >>> data = [(1, 'J'), (4, 'N'), (3, 'H'), (2, 'O')] >>> for item in data: ... heappush(heap, item) ... >>> while heap: ... print(heappop(heap)[1]) J O H N