15. median


#1

My code for task 15 is:

def median(listof):
    listof = sorted(listof)
    if len(listof) % 2 == 1:
        return listof[len(listof)//2]
    else:
        middleposition1 = listof[len(listof)//2-1]
        middleposition2 = listof[len(listof)//2+1]
        Median = (middleposition1 + middleposition2)/2
        return Median

It works right in Python Visualizer http://goo.gl/nKUQTQ and ideone.com http://ideone.com/mhe8Fq
But codecademy's interpreter says: > Oops, try again. median([4, 5, 5, 4]) returned 4.0 instead of 4.5
What's wrong with my code?


#2

different python version?

Consider:

$ python2
>>> 3 / 2
1
$ python3
>>> 3 / 2
1.5

In python 2 integer division results in an integer (floored)
In python 3 integers are thought of as "numbers" and division will produce a type that can represent the result better

Keep in mind that floats can't represent all numbers exactly and that in some situations you may want to use the integer division operator instead: //


#4

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