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 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]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值