Median: what is wrong with my code?


#1

Error displayed: Oops, try again. median([1]) resulted in an error: list index out of range


def median(numbers):
    new = sorted(numbers)
    mid = len(new) // 2
    if len(new) % 2 == 0:
        return (new[mid] + (new[mid + 1]))/2
    else:
        return new[mid + 1]

#2

@methodace32687,
What are doing with....

mid = len(new) // 2

Have look at
https://docs.python.org/2/library/operator.html#mapping-operators-to-functions

What argument do you use as you call the FUNCTION....??

I would suggest to use

    if len(new) % 2 == 0:
        return (new[mid] + (new[mid + 1]))/2.0
    else:
        return new[mid]

#3

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