15. Median: What's wrong with my code?


#1



In Practice Makes Perfect: 15. Median, I came up with this code.


Python tells me: "median([4, 5, 5, 4]) returned 5.0 instead of 4.5". Which I don't understand since I've already sorted the list. Where did I go wrong?


def median(numbers):
    snumbers = sorted(numbers)
    if len(snumbers) % 2 == 0:
        index1 = len(snumbers) / 2 
        index2 = index1 + 1 
        average = (snumbers[index1] + snumbers[index2]) / 2.0 
        return average
    else:
        index3 = len(snumbers)/2
        average = snumbers[index3] 
        return average


Thank you!


#2

Consider,

int(12 / 2)    # 6

This is the 7th element in the list, not the 6th. Because of zero-indexing, we need to remember the shift. The counterpart element is to the left of index [6].


#3

Got it! Silly mistake. Thank you!


#4

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