python PriorityQueue模塊 heapq模塊

Python heapq模塊

heap API

heapq.heappush(heap, item) #把item添加到heap中(heap是一個列表)

heapq.heappop(heap) #把堆頂元素彈出,返回的就是堆頂

heapq.heappushpop(heap, item) #先把item加入到堆中,然後再pop,比heappush()再heappop()要快得多

heapq.heapreplace(heap, item) #先pop,然後再把item加入到堆中,比heappop()再heappush()要快得多

heapq.heapify(x) #將列表x進行堆調整,默認的是小頂堆

heapq.merge(*iterables) #將多個列表合併,並進行堆調整,返回的是合併後的列表的迭代器

heapq.nlargest(n, iterable, key=None) #返回最大的n個元素(Top-K問題)

heapq.nsmallest(n, iterable, key=None) #返回最小的n個元素(Top-K問題)

代碼示例

import heapq
import random
 
# Top-K
mylist = list(random.sample(range(100), 10))
k = 3
largest = heapq.nlargest(k, mylist)
smallest = heapq.nsmallest(k, mylist)
print('original list is', mylist)
print('largest-'+str(k), '  is ', largest)
print('smallest-'+str(k), ' is ', smallest)
 
# heapify
print('original list is', mylist)
heapq.heapify(mylist)
print('heapify  list is', mylist)
 
# heappush & heappop
heapq.heappush(mylist, 105)
print('pushed heap is', mylist)
heapq.heappop(mylist)
print('popped heap is', mylist)
 
# heappushpop & heapreplace
heapq.heappushpop(mylist, 130)    # heappush -> heappop
print('heappushpop', mylist)
heapq.heapreplace(mylist, 2)    # heappop -> heappush

輸出結果

('original list is', [29, 87, 6, 88, 36, 93, 47, 1, 78, 44])
('largest-3', '  is ', [93, 88, 87])
('smallest-3', ' is ', [1, 6, 29])
('original list is', [29, 87, 6, 88, 36, 93, 47, 1, 78, 44])
('heapify  list is', [1, 29, 6, 78, 36, 93, 47, 88, 87, 44])
('pushed heap is', [1, 29, 6, 78, 36, 93, 47, 88, 87, 44, 105])
('popped heap is', [6, 29, 47, 78, 36, 93, 105, 88, 87, 44])
('heappushpop', [29, 36, 47, 78, 44, 93, 105, 88, 87, 130])
('heapreplace', [2, 36, 47, 78, 44, 93, 105, 88, 87, 130])

PriorityQueue 模塊

基本操作

常用put(入隊列)與get(出隊列),queue(查看隊列中的元素)。

put方法要注意方入隊列的是一個元組,不要忘記括號,默認情況下隊列根據元組的第一個元素進行排序。越小的優先級越低。

get方法是將優先級最低的一個元素出隊列

代碼示例

que = PriorityQueue()
que.put((10,'good'))
que.put((1,'nice'))
que.put((5,'fine'))
while not que.empty():
	print (que.get())

結果輸出

(1, 'nice')
(5, 'fine')
(10, 'good')

結合linklist

之所以總結了一下python排序運用比較靈活的兩個模塊,是看到了LeetCode的一道題 https://leetcode.com/problems/merge-k-sorted-lists/ ,相對於使用sorted 和 手寫快排的方法,的確這兩個模塊更靈活一些,而且效率也很好,而鏈表還是表常用或者嚐嚐考到的一個數據結構,所以拿出來總結一下。

參考文章

  1. 日常編程中的python-優先級隊列

  2. Python heapq模塊

  3. 如何理解算法時間複雜度的表示法O(n²)、O(n)、O(1)、O(nlogn)等

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章