數據結構堆(heap)是一種優先隊列。使用優先隊列能夠以任意順序增加對象,並且能在任意的時間(可能在增加對象的同時)找到(也可能移除)最小的元素,也就是說它比python的min方法更加有效率。
1、heappush(heap,n)數據堆入
In [1]: import heapq as hq In [2]: import numpy as np In [3]: data = np.arange(10) #將生成的數據隨機打亂順序 In [4]: np.random.shuffle(data) In [5]: data Out[5]: array([5, 8, 6, 3, 4, 7, 0, 1, 2, 9]) #定義heap列表 In [6]: heap = [] #使用heapq庫的heappush函數將數據堆入 In [7]: for i in data: ...: hq.heappush(heap,i) ...: In [8]: heap Out[8]: [0, 1, 3, 2, 5, 7, 6, 8, 4, 9] In [9]: hq.heappush(heap,0.5) In [10]: heap Out[10]: [0, 0.5, 3, 2, 1, 7, 6, 8, 4, 9, 5]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
2、heappop(heap)將數組堆中的最小元素彈出
In [11]: hq.heappop(heap) Out[11]: 0 In [12]: hq.heappop(heap) Out[12]: 0.5
- 1
- 2
- 3
- 4
- 5
3、heapify(heap) 將heap屬性強制應用到任意一個列表
heapify 函數將使用任意列表作為參數,並且盡可能少的移位操作,,將其轉化為合法的堆。如果沒有建立堆,那么在使用heappush和heappop前應該使用該函數。
In [13]: heap = [5,8,0,3,6,7,9,1,4,2] In [14]: hq.heapify(heap) In [15]: heap Out[15]: [0, 1, 5, 3, 2, 7, 9, 8, 4, 6]
- 1
- 2
- 3
- 4
- 5
- 6
4、heapreplace(heap,n)彈出最小的元素被n替代
In [17]: hq.heapreplace(heap,0.5) Out[17]: 0 In [18]: heap Out[18]: [0.5, 1, 5, 3, 2, 7, 9, 8, 4, 6]
- 1
- 2
- 3
- 4
- 5
5、nlargest(n,iter)、nsmallest(n,iter)
heapq中剩下的兩個函數nlargest(n.iter)和nsmallest(n.iter)分別用來尋找任何可迭代的對象iter中第n大或者第n小的元素。可以通過使用排序(sorted函數)和分片進行完成。
#返回第一個最大的數 In [19]: hq.nlargest(1,heap) Out[19]: [9] #返回第一個最小的數 In [20]: hq.nsmallest(1,heap) Out[20]: [0.5]