Median - Logic in right direction?


Practice makes perfect - Median
Can anybody tell me what is wrong with my code?Thanks

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

def median(lista):
    #return the median value of the list
    listaOrd = sorted(lista)
    middle = 0
    half = len(listaOrd) / 2
    half2 = half - 1
    for i in listaOrd:
        if len(listaOrd) == 1:
            return i
        elif i % 2 == 0:
            middle = (half + half2) / 2.0
            middle = sum(i for i in listaOrd) // len(listaOrd)
    return middle


Here's how to find the median manually:
1. You first sort the list of numbers. That step is ok.
2. If the # of items in the list is even, you take the average of the two middle numbers.
3. If the # of items in the list is odd, you take the middle number.

This doesn't require any loops as you don't need to iterate through the list. But, it requires 2 cases which I've listed above.


def median(lista):
#return the median value of the list
lOrdenado = sorted(lista)
middle = 0
if len(lOrdenado) == 1:
middle = lOrdenado[0]
middle = sum(lOrdenado) / len(lOrdenado)
return middle

This code works on another python interpreter but doesn't work on codeacademy ? Can you detect why?


The way to find the median is different between an even length list and an odd length list.
I suggest you build your code around those two cases: when list length is even and when list length is odd.

Ask yourself this: How would you find the median manually? Figure that out and code out the process.


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