The background is, there is a method most_common()
for the class Counter
but not a method least_common()
. As an exercise, if I were to add it to the class:
import collections
def least_common(self, n=None):
return (counter.most_common()[:-n-1:-1] if n != None
else counter.most_common()[::-1])
collections.Counter.least_common = least_common
but then it will contaminate the global space by creating an extra least_common
function. Is there a way to use an IIFE like in JavaScript, or use a lambda
? But lambda
doesn't seem to take default arguments?
P.S. and update: Initially, I tried default parameter value like this:
collections.Counter.least_common = lambda self, n=None:
return (counter.most_common()[:-n-1:-1] if n != None
else counter.most_common()[::-1])
And it won't work. It seems like I have to move the second line to the end of the :
on the first line, and I have to remove the return
for it to work.