# Median

#1

my code:

``````def median(inlis):      #    inlis(input list)
sorted(inlis)

if len(inlis)%2==0:
y=len(inlis)/2
x= (inlis[y] + (inlis[y+1]))/2.0

elif not len(inlis)%2==0 and not len(inlis)==1:
x=inlis[len(inlis)/2]

else:
x=inlis[0]

return x``````

Codeacademy result = " Oops, try again. median([6, 8, 12, 2, 23]) returned 12 instead of 8 "

#2

ok, i modify cod, and it's run

``````def median(inlis):  #inlis(input list)
inlist=sorted(inlis)

if len(inlist)%2==0:
y=len(inlist)/2
x= (inlist[y] + (inlist[y-1]))/2.0

elif not len(inlist)%2==0 and not len(inlist)==1:
x=inlist[int((len(inlist)/2)+0.5)]

else:
x=inlist[0]

return x``````

#3

hello there,

Why is my code not working ?

``````def median(test):
num = sorted(test)
x = num[len(num)/2]
y = num[len(num)/2+1]
z= (x+y)/2.0

if len(num) % 2 == 0 :
return z

elif not len(num)%2==0 and not len(num)==1:
return num[len(num)/2]
else:
return num[0]``````

it says :"Oops, try again. median([1]) resulted in an error: list index out of range"

#4

try y = num[len(num)/2 -1], because index of list started at 0, and index of list = len(list) - 1

#5

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