Median


#1

Please tell me where i have gone wrong.

ERROR:median([4, 5, 5, 4]) returned 5.0 instead of 4.5

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/median

def median(x):
  y=sorted(x)
  if len(y)%2==0:
    sum= float((y[len(y)/2]+y[(len(y)/2)+1])/2)
    return sum
  else:
    return y[len(y)/2]
print median([4,5,5,4])


#2

so for [4,5,5,4] the length is 4, the indexes are: 0, 1, 2, 3 so the middle two indexes are 1 and 2.

but according to your math the middle indexes are 2 and 3, that can’t be right?


#3

Thank you,I didnt think about that.But I still have a problem.


#4

the problem is that if the division involves two integers (9/2) python will round down to the nearest integer, you cast to float() but after the division so the damage (rounding down) has already been done, the division should involve a float


#5

Thanks a lot.Worked this time.


#6