15. Median can't return result


#1




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


The console keeps giving me a syntax error on line 9: SyntaxError: invalid syntax


Return statements aren't that complex, so I'm not understanding what is wrong. It should just return the value stored in final, right?


def median(old):
    new = sorted(old)
    if len(new) % 2 == 0:
        final = new[len(new)/2]
    elif len(new) % 2 != 0:
        sub = len(new)/2
        round(sub)
        final = ((new[m]+new[m+1]/2.0)
    return final


#2

turns out the syntax error was due to a missing parenthetical on line 7

def median(old):
    new = sorted(old)
    u=len(new)/2
    if len(new) % 2 == 0:
        final = new[u]
    elif len(new) % 2 != 0:
        m=round(u)
        final = ((new[m-1]+new[m])/2.0)
    return final

Now I am getting "median([1]) resulted in an error: list indices must be integers, not float"
Does len() output a float? any ideas?


#3

No, it does not, and neither should it ever be turned into one. It is a counting number. The real variable is in the numerator, in this case, so that should be treated as a float, explicitly (Python 2).

Personally, I loathe 2.0 as a way to define a float. Sure it works, but it is a bastardization of the semantics.


#4

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