Median - object of type 'NoneType' has no len()


#1



I keep looking over this and can't figure out what's wrong.. I keep getting the error: median([4, 5, 5, 4]) resulted in an error: object of type 'NoneType' has no len()

And I've double checked to make sure that anything related to length doesn't actually have "None" attributed, but still can't figure it out.

Anyone more experienced have any ideas?


def median(num): 
    middle = len(num) / 2.0 
    new = num.sort()
    if len(num) == 1:
        return num[0]
    elif len(new) % 2 != 0:
        return new[middle -.5]
    else:
        mean = new[middle] + new[middle - 1] / 2.0
        return mean.


#2

That should throw the first syntax error (the full stop is invalid syntax)

As for the runtime error, it should be showing in the console.

    elif len(new) % 2 != 0:
TypeError: object of type 'NoneType' has no len()

We can trace this back to the line,

new = num.sort()

new in this instance will be None since there is no return value from .sort(). This is an in-place sort that happens ON the object being sorted. To create a sorted copy, we use sorted(list)

new = sorted(num)

So fixing that we get a new exception raised:

    mean = new[middle] + new[middle - 1] / 2.0
TypeError: list indices must be integers or slices, not float

So this is the culprit. Okay, let's fix that,

middle = int(len(num) / 2)

Now we get no exceptions raised, but the result is incorrect.

>>> median([4,5,5,4])
7.0
>>>

Consider the arithmetic order of operations. In this line, in what order is the evaluation being done?

mean = new[middle] + new[middle - 1] / 2.0

Consider, middle == 2 in this instance.

mean = new[2] + new[1] / 2.0

     = 5 + 4 / 2.0

     = 5 + 2.0

     = 7.0

#3

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