Median exercise


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

it won't let me iterate the input to make it into a list, it wont let me add input to a list, and it wont let me treat it like a list.

def median (l):
    nl = l.sort() 
    l = len(nl)
    if l % 2 != 0:
       m = nl[(l-1)/2.0] 
       return m 
        m = (nl[(l/2)-1] + nl[(l/2)])/2.0
        return m


The sort() method does not create a copy, but sorts the object in place. nl in this case is None.


n = [9,4,7,2,8,3,1,6,2]
l = n.sort()
print l                  # None
print n                  # [1, 2, 2, 3, 4, 6, 7, 8, 9]

Try this, instead,

nl = sorted(l)


For a supplement, let's refactor your program, keeping the general principles in tact...

def median(s):
    u = sorted(s)
    v = len(u)
    n = int(v / 2)
    return u[n] if v % 2 else float(u[n-1] + u[n]) / 2

Any time code looks complicated, it probably is. We can never stop looking for ways to trim fat.