Median exercise


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096#

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 
    else:
        m = (nl[(l/2)-1] + nl[(l/2)])/2.0
        return m


#2

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

Consider:

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)

#3

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.