I need help on Median 15


#1



def median(x):
    sort = sorted(x)
    if len(x)%2 == 0:
        a = sort[len(x)/2-1]
        b = sort[len(x)/2]
        return (a+b)/2.0
        
    else:
        return sort[len(x)/2.0-0.5]


#2

I got "
Oops, try again. median([1]) resulted in an error: list indices must be integers, not float"


#3

In your else statement, the index you are passing needs to be wrapped in "int()", because when you divide by floats, Python passes a float back to you. Like so...

def median(x):
sort = sorted(x)
if len(x)%2 == 0:
a = sort[len(x)/2-1]
b = sort[len(x)/2]
return (a+b)/2.0

else:
    return sort[int(len(x)/2.0-0.5)]

Hope that helps!


#4

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