This is the python solution for the Leetcode problem – Top K Frequent Words – Leetcode Challenge – Python Solution.
Source – qiyuangong’s repository.
x
29
29
1
class Solution(object):
2
# def topKFrequent(self, words, k):
3
# """
4
# :type words: List[str]
5
# :type k: int
6
# :rtype: List[str]
7
# """
8
# counter = collections.Counter(words)
9
# res = sorted(counter.items(), cmp=cmp_frequency, reverse=True)
10
# return [k for k, _ in res[:k]]
11
12
# def cmp_frequency(x, y):
13
# if x[1] != y[1]:
14
# return cmp(x[1], y[1])
15
# return cmp(y[0], x[0])
16
17
# def topKFrequent(self, words, k):
18
# count = collections.Counter(words)
19
# candidates = count.keys()
20
# candidates.sort(key = lambda w: (-count[w], w))
21
# return candidates[:k]
22
23
def topKFrequent(self, words, k):
24
count = collections.Counter(words)
25
# Note that python heapq only support min heap
26
# So, we can make the value negative to create a max heap
27
heap = [(-freq, word) for word, freq in count.items()]
28
heapq.heapify(heap)
29
return [heapq.heappop(heap)[1] for _ in xrange(k)]