Heap: One of the priority queues that use the priority queue to increase the object in any order, and to find (or possibly remove) the smallest element at any time (possibly at the same time as the object is incremented), which is more efficient than the method used for min in the list.
Python does not have a separate heap type, only a module that includes some heap operation functions, called HEAPQ.
Import HEAPQ
1.heapq.heappush (Heap,item) #heap为定义堆, item added element;
eg.
Heap=[]
Heapq.heappush (heap, 2)
2.heapq.heapify (list) #将列表转换为堆
eg.
list=[5,8,0,3,6,7,9,1,4,2]
Heapq.heapify (list)
3.heapq.heappop (heap) #删除最小的值
eg.
Heap=[2, 4, 3, 5, 7, 8, 9, 6]
Heapq.heappop (heap)---->heap=[3, 4, 5, 7, 9, 6, 8]
4.heapq.heapreplace (Heap,item) #删除最小元素值, add a new element value
eg.
Heap=[2, 4, 3, 5, 7, 8, 9, 6]
Heapq.heapreplace (heap,11)------>heap=[2, 3, 4, 6, 8, 5, 7, 9, 11]
5.heapq.heappushpop (Heap,item) #首判断添加元素值与堆的第一个元素值对比, if it is greater then remove the smallest element, and then add a new element value, otherwise do not change the heap
eg.
Condition: Item >heap[0]
Heap=[2, 4, 3, 5, 7, 8, 9, 6]
Heapq.heappushpop (heap, 9)---->heap=[3, 4, 5, 6, 8, 9, 9,7]
Condition: Item
Heap=[2, 4, 3, 5, 7, 8, 9, 6]
Heapq.heappushpop (heap, 9)---->heap=[2, 4, 3, 5, 7, 8, 9,6]
6.heapq.merge (...) #将多个堆合并
7.heapq.nlargest (n,heap) #查询堆中的最大元素, n indicates the number of query elements
eg.
Heap=[2, 3, 5, 6, 4, 8, 7, 9]
Heapq.nlargest (1,HEAP)--->[9]
8.heapq.nsmallest (n,heap) #查询堆中的最小元素, n indicates the number of query elements
eg.
Heap=[2, 3, 5, 6, 4, 8, 7, 9]
Heapq.nlargest (1,HEAP)--->[2]
Python Learning Notes (heap usage in python)