Help on median


#1
def median(numbers):
    median=0
    numbers_sorted=sorted(numbers)
    length=len(numbers_sorted)
    even_ind=length/2
    even_lower=float(numbers[even_ind-1])
    even_upper=float(numbers[even_ind])
    for num in numbers_sorted:
        if length%2==0:
            median+=(even_lower+even_upper)/2.0
        else:
            from math import ceil
            odd_ind=int(ceil(length/2))
            median+=numbers[odd_ind]
        return median

Can anyone tell me what's wrong?
It says that for median([4,5,5,4]) it returns 5.0 instead of 4.5.


#2

Hi, I think I see it (I had a similar problem). Your definitions for even_lower and even_upper are referencing the original list ("numbers"), not the sorted list ("numbers_sorted").

Change those two lines and I think it will work. Good luck!


#3

My solution:

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

With comments:

def median(lst):
    # Put the input into a sorted list
    new = sorted(lst)
    # Get the midpoint of the list
    mid = len(lst) / 2
    # Check if the list has an even amount of elements
    if  len(lst) % 2 == 0:
        # If it does, then we need to get the average of the two. We get the second element by using [mid - 1]
        return (new[mid] + new[mid - 1]) / 2.0    
        # Otherwise we can just return the middle element
    else:
        return new[mid]

#4

Thanks! Can't believe I didn't notice that :smile: