堆
特点
- 堆是一个二叉树,它的每个父节点的值都只会小于或等于所有孩子节点(的值)
- 它使用了数组来实现:从零开始计数,对于所有的k,都有heap[k] <= heap[2k+1] <=heap[2k+2]
- 堆最有趣的特性在于最小的元素总在根节点:heap[0]
heapq.heapify(x) 将list x 转换成堆
import heapq
x=[4,5,6,7,9,1,2,3,0]
print(x)
heapq.heapify(x)
print(x)
heapq.heappush(heap, item) 将item 的值加入heap中,保持堆的不变性
import heapq
x=[4,5,6,7,9,1,2,3,0]
print(x)
heapq.heappush(x,8)
print(x)
heapq.heappop(heap) 弹出并返回heap的最小元素,保持堆的不变性。使用heap[0],可以访问最小的元素而不弹出它
import heapq
x=[4,5,6,7,9,1,2,3,0]
print(x)
heapq.heapify(x)
print(x)
heapq.heappop(x)
print(x)
heap.heappushpop(heap, item) 先将item放入堆中,然后弹出heap中最小元素并返回堆的值,堆大小保持不变
import heapq
x=[4,5,6,7,9,1,2,3,0]
print(x)
heapq.heapify(x)
heapq.heappushpop(x,8)
print(x)
heap.heapreplace(heap, item) 先弹出heap中最小元素,然后将item放入堆中并返回堆的值,堆大小保持不变
import heapq
x=[4,5,6,7,9,1,2,3,0]
print(x)
heapq.heapify(x)
heapq.heapreplace(x,8)
print(x)
heapq.merge(*iterables) 将多个已排序的输入合并为一个以排序的输出(例如:合并来自多个日志文件的带时间戳的条目)。返回已排序值的iterator.
import heapq
x = [5,15,62]
y = [1,7,34,56,88]
z = heapq.merge(x,y)
print(list(z))
heapq.nlargest(n, iterable) 从iterable所定义的数据集中返回前n个最大元素组成的列表
import heapq
x = [1,3,6,8,345,5,525,54,5568,656,33]
lg = heapq.nlargest(4, x)
print(lg)
heapq.nsmallest(n, iterable)) 从iterable所定义的数据集中返回前n个最小元素组成的列表
import heapq
x = [1,3,6,8,345,5,525,54,5568,656,33]
sm = heapq.nsmallest(4, x)
print(sm)