Median


#1

This seems like it should be simple, but is not returning the right answer. Why?



def median(x):
  b = sum(x)
  x = len(x)
  return b / x



#2

You are returning an average, not a median. The median is the middle data point in a sorted sample space. The middle will be the average of two middle data points in an even length sample.


#3

Ahh ok got - but still, my result returns 4 not 4.5 when given [4,5,5,4].

Why is that?


#4

It has to do with the way that Python 2 works with integers and floats in division.

int / int    => int

float / int  => float

Use the float() function on your numerator.

def median(sample):
    s = sorted(sample)
    n = len(s)
    m = int(n / 2)
    return s[m] if n % 2 else float(s[m - 1] + s[m]) / 2

#5

Can you convert an int to a float?


#6

Yes.

float(3) =>  3.0

I have an issue with converting counting numbers, though. It is a minor concern, but all the same, our code should make sense to the reader. That is why I suggested the numerator (which may be a float) as opposed to the denominator (which is a counting number).

When you see this,

(s[m - 1] + s[m]) / 2.0

the result is the same, but it is misleading the reader. Better we cast our suspicions on the variables than a literal constant.


#7

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