# 15/15 Not sure why this doesn't work

#1

def median(numlist):
low=numlist[0]
high=numlist[0]
median=0
for n in numlist:
if n<=low:
low=n
elif n>=high:
high=n
while low<=high:
if low==high:
median=low
elif low==high-1:
median=(low+high)/2
low=low+1
high=high-1
return median

#2

Try this one
def median(num):
n = len(num)
num = sorted(num)
if n%2 == 1:
m = n/2
#print m
s= num[m]
#print s
return s
else:
m = n/2
#print m
s = float ((num[m-1] + num[m]))/2
#print s
return s
num = [1, 2, 3, 4, 5]
median(num)

This works fine. Remember to indent

#3

This worked for me, see below But the bit I'm not getting is:

``mid = len(x) / 2``

When I test it with some print statements based on five elements "[5,4,3,2,1]". I get the mid point as 2. Its like its rounding down, i.e
mid = 5 / 2
mid = 2
I use mid as my index to the above list and get the answer 3

Why is this?
Is my code faulty or is this expected functionality?

Thanks,

Ed

``````def median(y):
x = sorted(y)
mid = len(x) / 2

if len(x) % 2 != 0:
#uneven number of elements
return x[mid]

else:
#even number of elements
dmid = mid - 1
result = float((x[dmid] + x[mid])) / 2
return result``````

#4

5 / 2 = 2 because both 5 and 2 are integers. Therefore you get an integer as a result.
However, 5.0 / 2.0 = 2.5 This is because we are now dividing floats.

I hope that helps.