"Paul McGuire" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > > "Paul McGuire" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > 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! > > Try this instead: > > 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 -- http://mail.python.org/mailman/listinfo/python-list