jov14
jov14

Reputation: 187

pure python implementation for calculating percentiles: what is the use of the lambda function here?

I have stumbled upon this pure python implementation for calculating percentiles here and here:

import math
import functools

def percentile(N, percent, key=lambda x:x):
"""
Find the percentile of a list of values.

@parameter N - is a list of values. Note N MUST BE already sorted.
@parameter percent - a float value from 0.0 to 1.0.
@parameter key - optional key function to compute value from each element of N.

@return - the percentile of the values
"""
   if not N:
       return None
   k = (len(N)-1) * percent
   f = math.floor(k)
   c = math.ceil(k)
   if f == c:
       return key(N[int(k)])
   d0 = key(N[int(f)]) * (c-k)
   d1 = key(N[int(c)]) * (k-f)
   return d0+d1

I get the basic principle behind this function and i see that it works correctly:

>>> percentile(range(10),0.25)
2.25

What I don't get is what the lambda function key=lambda x:x is there for. As far as i unterstand it, this lambda function simply returns the value that is passed to it. Basically, the whole function seems to yield the same result if i omit this lambda function altogether:

import math

def percentile2(N, percent):
"""
Find the percentile of a list of values.

@parameter N - is a list of values. Note N MUST BE already sorted.
@parameter percent - a float value from 0.0 to 1.0.
@parameter key - REMOVED

@return - the percentile of the values
"""
   if not N:
       return None
   k = (len(N)-1) * percent
   f = math.floor(k)
   c = math.ceil(k)
   if f == c:
       return N[int(k)]
   d0 = N[int(f)] * (c-k)
   d1 = N[int(c)] * (k-f)
   return d0+d1

If I test this:

>>> percentile2(range(10),0.25)
2.25

So what is the use of that lambda function, here?

Upvotes: 3

Views: 1795

Answers (3)

Aran-Fey
Aran-Fey

Reputation: 43196

It's right there in the documentation of the function:

@parameter key - optional key function to compute value from each element of N.

Basically, the percentile function allows the user to optionally pass a key function which will be applied to the elements of N. Since it is optional, it has been given the default value lambda x:x, which does nothing, so the function works even if the user omits the key parameter.

Upvotes: 2

Rob Watts
Rob Watts

Reputation: 7146

The answer is right there in the docstring (the string that starts on the line after the def statement):

@parameter key - optional key function to compute value from each element of N.

This allows you to use a list of something other than numbers. For example, your lambda could be lambda x:x.getRelevantValue() and your list would be one containing objects that have a getRelevantValue method.

Upvotes: 7

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798744

It's a tie-breaker in case f ever equals c. You haven't come across such a case, so your code never blows up (since key now doesn't exist).

Upvotes: -5

Related Questions