I am practicing leetcode question:
Leetcode Question:
Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
And I saw one of the discussions solve the problem with this. But I am not familiar with lambda, can anyone help me to understand what does lambda x: (-count[x], x)
mean? Thanks!!
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
count = Counter(words)
count = sorted(count, key = lambda x: (-count[x], x))
output = count[:k]
return output