15/15 Median. Better solutions


#1

def median(lst):
new = lst[:]
new = sorted(new)
odd = len(new) / 2.0 + 0.5 - 1
odd = int(odd)
even = len(new) / 2 - 1
even1 = len(new) / 2

if len(new) % 2 == 1:
return new[odd]
else:
value = new[even] + new[even1]
value2 = value / 2.0
return value2

I just used this solution for this section. It worked well, I knew what I had to do in my head. But I was wondering what better solutions you have? Ideally without having to do all the calculations at the top. Could you explain them?


#2

There are only two calculations (potentially)… The midpoint, and possibly the middle pair average… Given a sample space (a list)

s = sorted(sample)
n = len(s)
m = int(m / 2)

If the list has 8 elements, or 9 elements, the midpoint will be 4. This represents the upper value index in the middle pair. For an odd length list, the median is s[m] and if the length is even, the median is float(s[m-1] + s[m]) / 2


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.