本文主要是介绍Python heapq LeetCode 692. Top K Frequent Words,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
默认最小在最前,这个和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 heapqclass FreqWord:def __init__(self, word, freq):self.word, self.freq = word, freqdef __lt__(self, other):if (self.freq != other.freq):return self.freq < other.freqelse:return self.word > other.wordclass 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]
这篇关于Python heapq LeetCode 692. Top K Frequent Words的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!