# Median - Logic in right direction?

#1

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
else:
middle = sum(i for i in listaOrd) // len(listaOrd)
return middle``````

#2

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.

#3

def median(lista):
#return the median value of the list
middle = 0
else:
return middle

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

#4

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.

#5

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