Median


#1



I'm getting an error "median([1]) resulted in an error: list index out of range". I tried a few other things - I understand the error - sorted_seq[int((half_seq)+0.5)] is giving a number larger than 1. But I'm not sure how that's happening and how to fix.


seq = []
def median(seq):
    sorted_seq = sorted(seq)
    half_seq = float(len(sorted_seq)/2.0)
    if len(sorted_seq) % 2.0 != 0:
        return sorted_seq[int((half_seq)+0.5)]
    else:
        return (float(sorted_seq[int(half_seq)] + sorted_seq[(int((half_seq)+1))])/2.0)

print median


#2

for lists with an odd number of items, the length divided by two results in the middle index:

1 / 2 = 0
3 / 2 = 1
5 / 2 = 2
7 / 2 = 3

see? perfect. No need to add 0.5


#3

I changed it to :
return sorted_seq[int(half_seq)].
But now I'm getting an error for the second part: median([4, 5, 5, 4]) returned 5.0 instead of 4.5
What I tried to do in the code is to take the value of the 2nd place, and the value of the 3 place, and divide by 2.0 so I get the median.


#4

if you have the list [4,5,5,4], the indexes are: 0, 1, 2, 3. so the middle two indexes are 1 and 2, are you sure you have the right ones?


#5

Right, got it. Thanks!!


#6