Median


#1

    def median(sequence):
        x=sequence.sort()
        l=len(x)
        if l%2 ==1:
            y=x[(l-1)/2]
            return y
        elif l%2 ==0:
            p=x[(l/2)]
            q=x[(l/2)-1]
            r=(p+q)/2
            return r
        elif l==1:
            return x[0]

Don't know what's wrong with my code.

Oops, try again. median([1]) resulted in an error: object of type 'NoneType' has no len()


#2

Hi
use x=sorted(sequence) instead, as explained just before the instruction part

Moreover

This last elif is not necessary because it is already treated in the if l%2 ==1:.


#3

Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5


#4

p + q will be integer. When we divide by an integer, the quotient is the floor value, an integer, hence 4. Integer division implicitly yields an integer. To yield a float, we need to divide by a float (implicit) or declare a float in the numerator:

r = float( p + q ) / 2   # explicit
# or
r = ( p + q ) / 2.0      # implicit