Median works in idle but not in python


#1



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


Despite working as expected in Idle, I'm getting this error message on codeacademy: "Oops, try again. median([4, 5, 5, 4]) returned 4.0 instead of 4.5"


def median(numlist):
    if len(numlist) > 1:
        numlist = sorted(numlist)
        mid = len(numlist) / 2
        result = float
        if len(numlist) % 2 == 1:
            result = numlist[mid]
            return result
        else:
            mid1 = round(mid) -1
            mid2 = round(mid)
            mid2 = int(mid2)
            mid1 = int(mid1)
            m1 = numlist[mid1]
            m2 = numlist[mid2]
            result = float((m1 + m2)/2)
        return result
    else:
        return numlist[0]


#2

This line is not doing anything, so can be removed.

In Python 2 this will not compute the way one expects.

(m1 + m2) / 2

will be an integer, meaning it's already been floored. A float of that will not be correct.

float(m1 + m2) / 2

will return the correct result.


#3

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