Median


#1



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


It says "Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5" but when I run it in my Python shell it comes out as 4.5. Could it be a difference between version two and version 3 of python?


def median(lst):
    m = 0
    nlist = sorted(lst)
    if len(nlist) % 2 == 0:
        front = nlist[0:int(len(nlist)/2)]
        back = nlist[int(len(nlist)/2):]
        m = m + ((front[-1] + back[0]) / 2)
    else:
        m = m + nlist[int(len(nlist)/2)]
    return m.


#2

Yes there is a difference between the division in Python 2 and Python 3. Python 3's division can produce floats but for Python 2, it comes out as integers. Just put float() around it or divide by 2.0 instead of 2. I suggest doing the former (add float()).


#4

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