-2

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
AMC
  • 2,642
  • 7
  • 13
  • 35
Shin Yu Wu
  • 1,129
  • 4
  • 14
  • 23
  • [Lambda Expressions](https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions) in the the official Python tutorial. – AMC May 01 '20 at 11:50

1 Answers1

0

Lambdas are special case of functions that have no name and consist only of an implicit return statement.

def somename(x): return (-count[x], x)
count = sorted(count, key = somename)

is equivalent to yours

count = sorted(count, key = lambda x: (-count[x], x))

except it defines somename in the namespace.

Błotosmętek
  • 12,717
  • 19
  • 29
  • Thanks for your reply, but I don't understand why `(-count[x], x)`? How it be sorted? – Shin Yu Wu May 01 '20 at 12:00
  • Tuples are sorted lexicographically, ie. similarly to strings - by first element, if first elements are equal, then by second element etc. So sorting by `(-count[x], x)` sorts by `-count[x]`, but among values with the same count it simply sorts by x. – Błotosmętek May 01 '20 at 12:04