Three python features in one line of code
This post is based on this leetcode problem.
1 | # preludes |
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
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.