Median in a list of n elements

289 views Asked by At

I'm trying to determine the median of a list of n elements and I just can't see what I am doing wrong.

I have sorted(list) so that the elements are in the right order but I get a median of 5.0 instead of the correct 4.5.

My code looks like this.

def median(lista):
    median_even1 = 0
    median_even2 = 0
    median_sum = 0
    median_average = 0
    if len(lista) % 2 == 0:
        sorted(lista)
        median_even1 += lista[(len(lista)/2)]
        median_even2 += lista[(len(lista)/2 - 1)]
        median_sum = median_even1 + median_even2
        median_average = (median_sum) // (2.0)
        return median_average
    else:
        sorted(lista)
        return lista[(len(lista) / 2)]

Any suggestions?

3

There are 3 answers

1
DeepSpace On BEST ANSWER

sorted() isn't in place, it returns a new sorted list. Either reassign it (lista = sorted(lista)) or use list.sort() instead (lista.sort()).

0
Bobby On
>>> 5//2.0
2.0
>>> float(5)/2.0
2.5

//2.0 doesn't work in this case

0
TigerhawkT3 On

You can streamline a lot of that code while fixing the errors (sorted() not operating in place, len(lista)/2 being a floating-point number and therefore not a valid index value, using // with a float literal and presumably expecting a precise float, and so on).

def median(lista):
    lista = sorted(lista)
    half = len(lista)//2
    if half == len(lista)/2:
        return (lista[half]+lista[half-1])/2.
    return lista[half]