Median

#1

Hi, guys! Could anyone please explain why this code doesn't work correctly - it returns 5.0 instead of 4.5, I thinks that the mistake is somewhere after the "elif" statement, but I can't understand it and comments don't help. thanks in advance.

from math import *

def median(ar):
sorted(ar)
med = 0
l = len(ar)
if l%2 > 0:
ind = int(math.ceil(l/2) - 1)
med = ar[ind]
elif l%2 == 0:                  # Remainder from division (in this case 4%2 == 0)
ind1 = l/2                  # ind1 = 4/2 = 2.0
one = ar[int(ind1)]         # ar[2] = 5
ind2 = ind1 - 1             # ind2 = 2 - 1 = 1
two = ar[int(ind2)]         # ar[1] = 4
med = (one + two)/2.0       # (5 + 4)/2.0 = 4.5
return med

ar = [4, 5, 5, 4]
print median(ar)

#2

Remember, indexes start at 0. So the first number ,4, in the list [4, 5, 5, 4] has an index of 0 and not 1.

#3

I know it, but if ar = [1], then len(ar) = 1 in any case. I don't see my mistake that is connected with wrong indices count.

#4

Sorry, my bad. I forgot you need to sort the list so you have your indices right. However, you didn't store your sorted(ar). So you are using your unsorted list for everything.

#5

Oh, you are right))) I am a newcomer in programming so I often confuse such thing why I need create a new variable for new1 = sorted(some_list) and don't need create a variable for del(some_list[index]) or something like that. Thank you much for your help!)

#6

Haha no worries! I usually store things to a new variable if I ever need it for future use.

#9