少說話多寫程式碼之Python學習059——標準模組(堆)
heap堆是一種優先佇列,用優先佇列可以以任意順序增加物件。並且在任何時間找到最小元素。Python中有一個包含一些堆操作函式的模組heapq。包括如下函式,
heappush(heap,x) 將x入堆
heappop(heap) 將堆中最小的元素彈出
heapify(heap) 將heap屬性強制應用到任意列表
heapreplace(heap,x) 將堆中最小的元素彈出,同時將x入堆
nlargest(n,iter) 返回iter中第n大的元素
nsmallest(n,iter) 返回iter中第n小的元素看下面的使用,
from heapq import* from random import shuffle data= [0,1,2,3,4,5,6,7,8,9] shuffle(data) heap =[] for n in data: heappush(heap,n) print(heap) 輸出 [0, 1, 2, 3, 7, 6, 5, 9, 4, 8]
for n in data: heappush(heap,0.5) print(heap) 輸出 [0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 2, 4, 7, 1, 3, 0.5, 9, 6, 8, 0.5, 5]
heappush用於增加堆的項,用於堆函式建立的列表中,因為堆的列表有一定的順序。這裡雖然看起來順序隨意,但是是有規律的,位於i處的元素總是比i/2處的元素大。這個特性稱之為堆屬性。
heappop彈出最小的元素,一般彈出索引0處的元素,彈出後確保剩餘元素中最小的元素佔在這個位置。
print(heappop(heap)) print(heappop(heap)) print(heap) 輸出 0 0.5 [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 1, 3, 9, 6, 7, 8, 5, 2, 4]
heapify使用任意列表作為引數,將其轉換為合法的堆。
heap=[1,2,3,5,4,8,9.7] heapify(heap) print(heap) 輸出 [1, 2, 3, 5, 4, 8, 9.7]
heapreplace彈出堆的最小元素,並且將新元素推入。它比heappop後再heappush效率高。
heapreplace(heap,0.5) print(heap) 輸出 [0.5, 2, 3, 5, 4, 8, 9.7]
heapreplace(heap,10) print(heap) 輸出 [2, 4, 3, 5, 10, 8, 9.7]
堆的主要函式就瞭解到這裡,記住堆的屬性:i位置處的元素總比2i以及2i+1索引處的元素小。
工程檔案下載:ofollow,noindex" target="_blank">https://download.csdn.net/download/yysyangyangyangshan/10844403