Help With Median


#1




i get this error
Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5

I tried to change my / 2 into a / 2.0 as i need a float for the answer. I change all the division to floats and get another error
Oops, try again. median([4, 5, 5, 4]) resulted in an error: list indices must be integers, not float

im confused pls help me =[


def median(lst):
    new_lst = sorted(lst)
    lenth = len(new_lst)
    if lenth % 2 == 0:
        return (new_lst[lenth/ 2] + new_lst[lenth / 2]) / 2.0
    else:
        return new_lst[lenth/ 2]


#2

once [4, 5, 5, 4] is sorted you have [4, 4, 5, 5], right? so you need the middle two items, lets call them left middle and right middle (in case if a list has 4 items, this are index 1 and index 2)

but in your case, you only get the right middle + right middle / 2.0 instead of left middle + right middle / 2.0, understand what i mean?


#3

Ah yes! I see what you mean. In fact i had tried this once already, I used "- 1" from the right middle to get the left middle but i may be doing it wrong since i now have the error:

Oops, try again. median([1, 34, 1, 6, 8, 0]) returned 5.5 instead of 3.5

I changed this line of code:

return ((new_lst[lenth/ 2] ) + ((new_lst[lenth / 2]) - 1 )) / 2.0


#4

but the -1 is to manipulate the index, the index is determined inside the square brackets so you should have:

new_lst[lenth / 2 -1]

with 5 and 4 you are very lucky, given 5 -1 equals 4.


#5

Ahhh I see! Your right, god knows why i didn't think of that since i had it like that once and changed it because of another error hahaha.

It works! it finally works!
thank you very much!


#6