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


#1

This is my code and above is my error. What do I need to change?? It seems alright in my perspective.

def median(numbers):
    lst = sorted(numbers)
    print lst
    if len(lst) == 1:
        return lst[0]
    elif len(lst) % 2 == 0:
        return lst[len(lst) / 2 - 1] + lst[len(lst) / 2] / 2.0
    else:
        return lst[len(lst) - 1 / 2]

Thank you for your help!

THIS IS WHAT I DID TO FIX IT!!! VVVVVV

def median(numbers):
    lst = sorted(numbers)
    print lst
    n = len(lst)
    if n == 1:
        return lst[0]
    elif n % 2 == 0:
        return (lst[(n / 2) - 1] + lst[n / 2]) / 2.0
    else:
        return lst[(n - 1) / 2]

#2

There are two problems and both of them are due to operator precedence.

surround you elif's expression using ()(brackets) then divide it by 2.0

In final else part, due to operator precedence 1/2 is calculated first which comes to be 0 and so we will get out of index error, You can fix it same way (using ())


#3

Often our perspective is clouded by blindness to our own mistakes. The way to improve is to question our own work and look for ways to simplify.

shows up four times in your code. This could be cached.

n = len(lst)

This conditional is not needed. 1 is an odd length so will be handled in the odd branch.

if n % 2:
    return lst[n / 2]

When n is 1, the return value will be lst[0] (in Python 2).

Work at simplifying your code and see if your solution isn't easier to work through.


#4

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