15. median error


#1


15. median

Oops,try again. median([4,5,5,4]) returned 5 instead of 4.5

When running the code in pyScripter I get the correct value (4.5)


def median(a):
    a=sorted(a)
    l=len(a)
    if len(a)%2 == 0.:
        m=(a[int(l/2)]+a[int(l/2)-1])/2
    else:
        if l < 2:
            m=a[0]
        else:
            m=a[int(l/2)]
    return m


#2

This line:

m=(a[int(l/2)]+a[int(l/2)-1])/2

this will give 5 + 4 which is 9, then divided by 2 = 5. A integer (a non decimal number) divided by a integer gives a integer.

How to solve this problem? Either divide by a a float (decimal number) or cast it to a float using float()


#3

As far as I can see @stetim94 is correct that the problem is caused by this line and not using float division:

m=(a[int(l/2)]+a[int(l/2)-1])/2

So to solve it you need to make the dividend or divisor or both become a floating point number e.g. by literally adding a point:

m=(a[int(l/2)]+a[int(l/2)-1])/2.

or using the float() but as said use it on the dividend or the divisor as float((4+5)/2) will only yield 4. and not 4.5 . The reason why it works on your local environment is probably because you're using python3 there and there was a change to remove the ambiguity of the division operator:
https://www.python.org/dev/peps/pep-0238/

What really confuses me here is that you say you get 5 instead of 4 because integer division is a floor division to the next integer. Meaning it should round downwards (always), it is not rounding upwards and trying it in the CC editor yielded a 4 to me not a 5.


#4

I was indeed working with puthon 3 in my local environment where the / operation returns a float.
I checked again the initial code in the CC editor and the return value is 4 and not a 5.
Thank you very much to both of you for your help.