Mean, median, and mode - third time's the charm!!!

Paul McGuire ptmcg at austin.rr._bogus_.com
Mon Dec 6 21:31:18 CET 2004

```"Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message
news:Ou2td.117149\$jq5.23748 at fe2.texas.rr.com...
>
> "Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message
> news:E01td.116586\$jq5.8973 at fe2.texas.rr.com...
> > This median expression is incorrect.  median is *not* the midpoint
between
> > max and min values.  It is the middle value when all values are sorted
> (for
> > an odd number of values), or the average of the two middle values when
all
> > values are sorted (for an even number of values).
> >
> > In Python 2.4 (needed to use sorted() built-in), this can be one-lined
as:
> > median = lambda x: ((x % 2) and (sorted(x)[len(x)>>1]) or
> > (sum(sorted(x)[(len(x)>>1):(len(x)>>1)+1])/2))
> >
> > (not yet tested, as I've not installed v2.4 yet)
> > With boolean short-circuiting, this should only sort the list once.
> >
> > -- Paul
> >
> >
> Damned off-by-one errors!
>
>
> median = lambda x: ((len(x) % 2) and (sorted(x)[(len(x)>>1)-1]) or
> (sum(sorted(x)[((len(x)>>1)-1):(len(x)>>1)])/2))
>
>
> Or using the sneaky None returned by sort(), for pre-2.4 utility:
>
> median = lambda x: x.sort() or ((len(x) % 2) and (x[(len(x)>>1)-1]) or
> (sum(x[((len(x)>>1)-1):(len(x)>>1)])/2))
>
>
> -- Paul
>
>

median = lambda x: x.sort() or ((len(x) % 2) and (x[(len(x)>>1)])) or
(sum(x[((len(x)>>1)-1):(len(x)>>1)+1])/2.0)

>>> median( [2,3,4,5,6,7])
4.5
>>> median( [2,3,4,5,6])
4

```