Median


#1



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


My median([4, 5, 5, 4]) returned 4 instead of 4.5


I think everything is right but it just goes wrong. Please help me find what's the problem.


def median(sequence):
    result=0
    s=sorted(sequence)
    if len(s)%2==0:
        result=(s[len(s)/2-1]+s[len(s)/2])/2
    elif len(s)%2==1:
        result=s[(len(s)-1)/2]
    return result


#2

here:

result=(s[len(s)/2-1]+s[len(s)/2])/2

this would result in:

9 / 2

which is 4, the problem is that python floors/round down if the division involves two integers. You will have to use a float, one way or another so python doesn't floor the result, i will leave that for you to figure out


#3

In python 2.x if you divide an int by an int it will round the figure so the output is an int. If you divide an int by a float, even if the output is a whole number the output will be a float.

So given that, all your values are ints and so the output will always be an int and rounded.

Note: should you ever use python 3.x it will automatically output a float if an int divided by another int isn't a whole number.

That should help you, if not this hint from the lesson pretty much tells you exactly what you need to change:


Last but not least, note that (2 + 3) / 2 is not the same as (2 + 3) / 2.0! The former is integer division, meaning Python will try to give you an integer back. You'll want a float, so something like (2 + 3) / 2.0 is the way to go.

#4

Oh! Thanks, it work! I'll remember that.


#5

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