algorithms

Algorithm implementations
git clone git://git.laack.co/algorithms.git
Log | Files | Refs | README

top-k-frequent-words.py (490B)


      1 import heapq
      2 
      3 class Solution:
      4     def topKFrequent(self, words: List[str], k: int) -> List[str]:
      5         
      6         counts = {}
      7         for word in words:
      8             if word in counts:
      9                 counts[word] += 1
     10             else:
     11                 counts[word] = 1
     12         
     13         heap = []
     14 
     15         for word in counts:
     16             heappush (heap, (-counts[word], word))
     17 
     18         res = []
     19         
     20         for i in range(k):
     21             res.append(heappop(heap)[1])
     22         return res