Python heapq使用詳解及實(shí)例代碼
Python heapq 詳解
Python有一個(gè)內(nèi)置的模塊,heapq標(biāo)準(zhǔn)的封裝了最小堆的算法實(shí)現(xiàn)。下面看兩個(gè)不錯(cuò)的應(yīng)用。
小頂堆(求TopK大)
話說需求是這樣的: 定長(zhǎng)的序列,求出TopK大的數(shù)據(jù)。
import heapq
import random
class TopkHeap(object):
def __init__(self, k):
self.k = k
self.data = []
def Push(self, elem):
if len(self.data) < self.k:
heapq.heappush(self.data, elem)
else:
topk_small = self.data[0]
if elem > topk_small:
heapq.heapreplace(self.data, elem)
def TopK(self):
return [x for x in reversed([heapq.heappop(self.data) for x in xrange(len(self.data))])]
if __name__ == "__main__":
print "Hello"
list_rand = random.sample(xrange(1000000), 100)
th = TopkHeap(3)
for i in list_rand:
th.Push(i)
print th.TopK()
print sorted(list_rand, reverse=True)[0:3]
大頂堆(求BtmK小)
這次的需求變得更加的困難了:給出N長(zhǎng)的序列,求出BtmK小的元素,即使用大頂堆。
算法實(shí)現(xiàn)的核心思路是:將push(e)改為push(-e)、pop(e)改為-pop(e)。
class BtmkHeap(object):
def __init__(self, k):
self.k = k
self.data = []
def Push(self, elem):
# Reverse elem to convert to max-heap
elem = -elem
# Using heap algorighem
if len(self.data) < self.k:
heapq.heappush(self.data, elem)
else:
topk_small = self.data[0]
if elem > topk_small:
heapq.heapreplace(self.data, elem)
def BtmK(self):
return sorted([-x for x in self.data])
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
Python自動(dòng)創(chuàng)建Markdown表格使用實(shí)例探究
Markdown表格是文檔中整理和展示數(shù)據(jù)的重要方式之一,然而,手動(dòng)編寫大型表格可能會(huì)費(fèi)時(shí)且容易出錯(cuò),本文將介紹如何使用Python自動(dòng)創(chuàng)建Markdown表格,通過示例代碼詳細(xì)展示各種場(chǎng)景下的創(chuàng)建方法,提高表格生成的效率2024-01-01
python 劃分?jǐn)?shù)據(jù)集為訓(xùn)練集和測(cè)試集的方法
今天小編就為大家分享一篇python 劃分?jǐn)?shù)據(jù)集為訓(xùn)練集和測(cè)試集的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2018-12-12
TensorFlow實(shí)現(xiàn)數(shù)據(jù)增強(qiáng)的示例代碼
?TensorFlow數(shù)據(jù)增強(qiáng)?是一種通過變換和擴(kuò)充訓(xùn)練數(shù)據(jù)的方法,本文主要介紹了TensorFlow實(shí)現(xiàn)數(shù)據(jù)增強(qiáng)的示例代碼,具有一定的參考價(jià)值,感興趣的可以了解游戲2024-08-08
python產(chǎn)生模擬數(shù)據(jù)faker庫(kù)的使用詳解
這篇文章主要介紹了python產(chǎn)生模擬數(shù)據(jù)faker庫(kù)的使用詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
Django數(shù)據(jù)庫(kù)操作的實(shí)例(增刪改查)
下面小編就為大家?guī)?lái)一篇Django數(shù)據(jù)庫(kù)操作的實(shí)例(增刪改查)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2017-09-09

