Three python features in one line of code

This post is based on this leetcode problem.

1
2
3
4
5
6
7
8
9
# preludes
# from collections import *
class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
try:
return max(Counter([i for i in nums if not i % 2]).items(), key=lambda x:(x[1], -x[0]))[0]
except:
return -1

In this problem, we are trying to get the most frequent even number in a sequence, if there's multiple most frequent answers, we take the smallest one. E.g. for a sequence of number , the smallest of most frequent numbers is .

We first use a list comprehension to get the even values followed by putting them on the init values of Counter() class from the collections module to get a counter for the list of numbers. Then use .items() method to convert the Counter object, which is actually a dict, to a list to tuples that looks like (number, frequency). We then use a max function we a key argument to get the most frequent element and the smallest one. What we do here is to create a tuple for each key, x[1] means we want the most frequent ones first, -x[0] means we want the smallest number first. Putting them in a tuple means we want the one that fulfils both conditions but the first one has a higher priority. We then ask for the first item in the sorted list and return that value. Finally, we wrap the whole line with a try and except block because if there's no even number, the length of the list comprehension will be zero, and max function will raise an error.