Median Code


#1



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


Error: median([1]) resulted in an error: list indices must be integers, not float


This code works fine in IDE but codecademy IDE is giving me the above error. what's wrong with it?


import math

def median(med):
    med = sorted(med)
    medi = 0
    if(len(med)%2 == 0):
        mid = math.floor(len(med)/2)
        medi = (med[mid] + med[mid -1])/2
    else:
        medi = med[math.floor(len(med)/2)]

    return medi


#2

Now I've removed the math module, still the error exist , while the IDE doesn't give me any error

this is the error now: median([4, 5, 5, 4]) returned 4 instead of 4.5

Here's the code:

def median(med):
    med = sorted(med)
    medi = 0
    if(len(med)%2 == 0):
        mid = len(med)//2
        medi = (med[mid] + med[mid -1])/2
    else:
        medi = med[len(med)//2]

    return medi

#3

the math method has a problem: It will give you floats (numbers with decimal), you can't use floats to access indexes on array. And why use floor anyway? A integer divided by a integer returns a integer. Which seems you have figured out hee:

mid = len(med)//2

no need to use //, / will also return a integer. Which is the problem you encounter here:

medi = (med[mid] + med[mid -1])/2

in case of your 4,5,5,4 this will be: 5 + 4 / 2 which is 9 / 2 = 4.5, but because this is a integer divided by a integer, this will be floored to 4. To solutions:

divided by a float (2.0 rather then 2) or cast it to a float using float()


#4

i think they want the function to return float not integer , you can use this function float()
for example : medi = float(med[mid] + med[mid -1])/2


#6

Casting to float solved the problem.
thanks