一、堆

1.最小堆 【Python heapq模块】

heap为定义堆,item增加的元素 heapq.heappush(heap,item)

>>> import heapq
>>> h = []
>>> heapq.heappush(h,2)
>>> h
[2]

将列表转换为堆 heapq.heapify(list)

>>> list = [1,2,3,5,1,5,8,9,6]
>>> heapq.heapify(list)
>>> list
[1, 1, 3, 5, 2, 5, 8, 9, 6]

删除最小值,因为堆的特征是heap[0]永远是最小的元素,所以一般都是删除第一个元素 heapq.heappop(heap)

>>> list
[1, 1, 3, 5, 2, 5, 8, 9, 6]
>>> heapq.heappop(list)
1
>>> list
[1, 2, 3, 5, 6, 5, 8, 9]

删除最小元素值,添加新的元素值 heapq.heapreplace(heap.item)

>>> list
[1, 2, 3, 5, 6, 5, 8, 9]
>>> heapq.heapreplace(list,99)
1
>>> list
[2, 5, 3, 9, 6, 5, 8, 99] 

首先判断添加元素值与堆的第一个元素值对比,如果大,则删除第一个元素,然后添加新的元素值,否则不更改堆 heapq.heapreplace(heap,item)

>>> list
[2, 5, 3, 9, 6, 5, 8, 99]
>>> heapq.heappushpop(list,6)
2
>>> list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> heapq.heappushpop(list,1)
1
>>> list
[3, 5, 5, 9, 6, 6, 8, 99] 

将多个堆合并 heapq.merge(…)

>>> list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> h
[1000]
>>> for i in heapq.merge(h,list):
... print(i,end=" ")
...
3 5 5 9 6 6 8 99 1000

查询堆中的最大元素,n表示查询元素个数  heapq.nlargest(n,heap)

>>> list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> heapq.nlargest(3,list)
[99, 9, 8]
>>>

查询堆中的最小元素,n表示查询元素的个数 heapq.nsmallest(n,heap)

>>> list
[3, 5, 5, 9, 6, 6, 8, 99]
>>> heapq.nsmallest(3,list)
[3, 5, 5]

2.最大堆

用heapy建立大顶堆:将数据以相反数的形式存入堆,再以相反数的形式取出

push(e)  --->>> push(-e)
pop(e) --->>> pop(-e)

  

参考文献:

【1】python3入门之堆(heapq)

04-23 04:17