15/15 What's wrong with my code?


#1

Here's my code:

def median(x):
x = sorted(x)
if len(x) == 1:
return x[0]
elif len(x) % 2 != 0:
return x[(int(len(x)/2))]
else:
a = x[int(len(x)/2)]
b = x[int((len(x)/2)-1)]
return (a + b)/2

It keeps saying "
Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5"
but it returns 4.5 when I run the code in the IDLE?
What's the problem?


#2

`def median(lst):
lst.sort()
print lst
print len(lst)
lstmedian=0
if len(lst)%2 != 0:
lstmedian= (len(lst)-1)/2
return lst[lstmedian]
else:
lstmedian2= ((len(lst)/2) - 1)
lstmedian3=len(lst)/2
lstmedian4= float((lst[lstmedian2]+lst[lstmedian3])/2.0)
return lstmedian4

lst=[5,6,7,2,3,4]
print median(lst)`

you can check my code , please use float instead of int to get the correct result

your code should be something like this :slightly_smiling:

def median(x):
x = sorted(x)
if len(x) == 1:
return x[0]
elif len(x) % 2 != 0:
return float(x[(int(len(x)/2))])
else:
a = float(x[int(len(x)/2)])
b = float(x[int((len(x)/2)-1)])
return (a + b)/2


#3

Thanks! You exactly pointed out my problem


#4

I think the problem is with older version of python it converts 4.5 (9/2) to 4 even. Using pythin 3+ we dont need to convert it into float again .
So we have to save the median value as float in earlier version of python and then divide by to get the value in float i.e 4.5

def median(ilist):
slist = sorted(ilist)
if (len(slist)%2 == 0):
return ( (slist[int(len(slist)/2)] + slist[int(len(slist)/2)-1])/2)
else:
return ( slist[int(len(slist)/2)])

Above code works fine locally using python 3.4