Median Error

#1

Hi Everyone, if anyone can help I would much appreciate it.
I'm trying to write a code to get the median of a list
my code seem to mess up when I have multiple item of the same value in a list. it keep spitting out this message: " Oops, try again. median([1, 34, 1, 6, 8, 0]) returned 1 instead of 3.5"

which is right btw, but I don't understand why is my code not taking route 'a' instead of 'c' since r is an even number

``````def median(n):
m = sorted(n)
result = 0
r = len(m)/2.0
if r % 2 == 0:
print 'a'
result =(m[int(r-1)] + m[int(r)])/2.0

elif r==0:
print 'b'
result= m[0]

else:
print 'c'
result= m[int(r-0.5)]

return result``````

#2

because `r` contains length of the list divided by 2?

the if condition should check the length of the list, not half the length

#3

the if condition checks if r is even or not, if it is even it should take the number at the the index r + (r-1) and divide them by 2 to get the median

#4

but if the length is 6, then half the length of 3, so then this condition:

``3 % 2 == 0``

would be false, but it should be true, since the list contains an even number of items

#5

got it.

here is what I did, now it works like a charm,

def median(n):
m = sorted(n)
result = 0
r = len(m)
i = r/2.0
if r % 2 == 0:
print 'a'
result =(m[int(i)] + m[int(i-1)])/2.0

elif r==0:
print 'b'
result= m[0]

else:
print 'c'
result= m[int(i-0.5)]

return result

Thank you so much @stetim94

#6

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