# 15/15 practice makes perfect

#1

I've written the code below and it passes when i use it in IDLE with any combination of numbers, however I am getting an error median([1]) returned -0.5 instead of 1 in codecademy.

Anyone have any help as to why it isn't passing or what I have missed?

numbers = []

def median(numbers):
new = []
result = 0
new = sorted(numbers)
if len(numbers)/2 != 0:
result = len(new) / 2
return new[result]
else:
result = ((len(new) / 2 ) + (len(new) / 2 - 1)) / 2.0
return result

median(numbers)

#2

i don't know thy it hasnt tabbed out correctly, but i have tabbed out under the def median(): then tabbed out twice in the if statement as in my screenshot below. cheers!

#3

i've changed the len(new) / 2 -1 to a +1 at the end as I realised that bit was wrong

#4

that line should be

``if len(new)%2 !=0``

and you have to do

``result = (new[len(new)/2] + new[len(new)/2 - 1])/2.0``

#5

I've made it work with using a little slice notation:

``````def median(lst):
lst  = sorted(lst)
if len(lst) == 1:
return lst[0]
elif len(lst) % 2 == 0:
mid1 = lst[(len(lst) / 2) - 1]
mid2 = lst[(len(lst) / 2)]
return (mid1 + mid2)  / (2.0)
else:
return lst[(len(lst) / 2)]``````

#6

Thanks for your help guys! That helped to clear it up for me nicely - I think I was just getting myself a bit tied in knots