Home >Backend Development >Python Tutorial >Is there a heap in python?
Heap (English: heap) is the collective name for a special type of data structure in computer science;
The definition of heap: a sequence of n elements { k1,k2,ki,…,kn} If and only if the following relationship is satisfied, it is called a heap. (Recommended learning: Python video tutorial)
"ki<=k2i,ki<=k2i+1;或ki>=k2i,ki>=k2i+1.(i=1,2,…,[n/2])"
This is the standard heap definition, but there is no independent heap type in python, it is just a module that contains some heap operation functions (heapq = the first letter of heap queue), in fact, the heap is a special list in python;
Briefly introduce the methods in heapq
import heapq 1.heapq.heappush(heap,item) #heap为定义堆,item 增加的元素; 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) #删除最小元素值,添加新的元素值 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) #首判断添加元素值与堆的第一个元素值对比,如果大于则删除最小元素,然后添加新的元素值,否则不更改堆 eg. 条件: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] 条件: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表示查询元素个数 eg. heap=[2, 3, 5, 6, 4, 8, 7, 9] heapq.nlargest (1, heap)--->[9] 8.heapq.nsmallest(n, heap) #查询堆中的最小元素,n表示查询元素个数 eg. heap=[2, 3, 5, 6, 4, 8, 7, 9] heapq.nlargest (1, heap)--->[2]
More Python related technologies Article, please visit the Python Tutorial column to learn!
The above is the detailed content of Is there a heap in python?. For more information, please follow other related articles on the PHP Chinese website!