Median, What's wrong with my code?


#1



Median 15/15


Oops, try again. median([4, 5, 5, 4]) returned 5 instead of 4.5


def median(lst):
    sorted(lst)
    if len(lst) % 2 == 0:
        first_index = len(lst) / 2
        second_index = first_index - 1
        average = ((lst[first_index]) + (lst[second_index])) / 2
        return average
    else:
        index = len(lst) / 2
        return lst[index]


#2

The above does not perform an in-place sort.

lst.sort()

does that. Your line needs to be assigned to a variable which will then be the sorted list.


#3

Line 6:
average = ... + ... / 2

needs to be 2.0 instead of 2.
just putting 2 forces an integer result (e.g. 4.5 would incorrectly return as 4)


#4

Not the best advice. That is fudging a counting number into a float, implicitly. Better to use explicit float() on the numerator.

float( a + b ) / 2

#5

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