# Median([1, 34, 1, 6, 8, 0]) returned 4.5 instead of 3.5

#1

median([1, 34, 1, 6, 8, 0]) returned 4.5 instead of 3.5

I know I'm really close. The error in my code lies somewhere in the else statement. Can someone point me in the right direction?

``````def median(alist):
blist = sorted(alist)
if len(alist) % 2 == 1:
return (blist[((len(alist))/2)])
else:
return (blist[(len(alist)/2)-1] + blist[(len(alist)/2)+1])/2.0``````

#2

Remove `+ 1`.

``x[m - 1] + x[m]``

#3

::sheepish:: well i guess that makes sense. can you help me understand why?

#4

Let's examine a couple of lists:

``````x = [2, 5, 7, 13, 17, 25, 31, 33]
0  1  2   3   4   5   6   7       <= index

y = [2, 5, 7, 13, 17, 25, 31, 33, 37]
0  1  2   3   4   5   6   7   8   <= index``````

The length of list 1 is even, of list 2, odd. The difference in length is 1.

``````n = len(y)                 # 9
m = int(n / 2)             # 4

print (y[m])               # 17``````

Notice that in list x the 4th index is the second of the middle pair?

``print (x[m - 1] + x[m])    # 30``

#5

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