# 15.median

#1

whats wrong with my code?
def median(h):
sorted(h)
if h.length % 2 == 0:
return (len(h) -1) / 2.0
else:
return (len(h)+1) / 2.0

#2

The "sorted(h)" line is where the problem lies.

Although all the other python documents (such as Python.org) say that using

sorted(3,2,1)

will result in

1,2,3

It would appear the right command would either be

number = [3,2,1]

#####

number = sorted (number)

#or

number.sort ()

and that will result in a sorted number.

I'm currently in another computer that doesn't have any Python IDE, so I can't check this out other than using codeacademy's console to see whether it's just a bug at the site, or if it's truly what is wrong.

And I think at first glance your median formula might be wrong. I could be wrong though. Check it again.

#3

why does this not work?
def median(number):
number = sorted (number)
if len(number) % 2 == 0:
return (number[len -1]) +(number[len]) / 2.0
else:
return number[len + 1] / 2.0

#4

Here is my code that worked. A little math intensive

def median(x):
newlist = sorted(x)
if len(newlist) == 1:
return newlist[0]
elif len(newlist) % 2 == 0:
return (((newlist[(len(newlist) / 2) - 1]) + (newlist[(len(newlist) / 2)])) / 2.0)
else:
return newlist[(len(newlist) / 2)]
return result

#5

thanks

#6

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