默认最小在最前,这个和sorted一样,没有reverse,但是可以用tuple来玩
heapq是module(文件),所以import
heapq.heappush是直接调用这个module最外层的函数
import heapq
h1 = []
heapq.heappush(h1, (5, 'write code'))
heapq.heappush(h1, (7, 'release product'))
heapq.heappush(h1, (1, 'write spec'))
heapq.heappush(h1, (3, 'create tests'))
print(heapq.heappop(h1))
#(1, 'write spec')
h2 = [(7,'7'),(6,'6'),(5,'5'),(4,'4'),(3,'3'),(2,'2'),(1,'1')]
heapq.heapify(h2)
print(h2)
#[(1, '1'), (3, '3'), (2, '2'), (4, '4'), (6, '6'), (7, '7'), (5, '5')]
-------------------------
来个LeetCode题目玩一玩,涉及到Python的重载:
from collections import Counter
import heapq
class FreqWord:
def __init__(self, word, freq):
self.word, self.freq = word, freq
def __lt__(self, other):
if (self.freq != other.freq):
return self.freq < other.freq
else:
return self.word > other.word
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
cw = Counter(words)
heap = []
for word, freq in cw.items():
heapq.heappush(heap, FreqWord(word, freq))
if len(heap) > k:
retire = heapq.heappop(heap)
heap.sort(reverse=True)
return [x.word for x in heap]