15/15 Median. Bug or my mistake?


#1



Hi, Community!
I was solving the last task from this block and stuck here. I was solving this in Visual Studio Code and the code below worked great there, but here it says, "Oops, try again. median([1]) resulted in an error: list indices must be integers, not float "
What is wrong?




def median(_list):
    sorted_list = sorted(_list)
    result = 0
    length = len(sorted_list)
    if length % 2 == 0:
        mid_val1 = sorted_list[round(length/2)]
        mid_val2 = sorted_list[round((length/2)-1)]
        result = (mid_val1 + mid_val2)/2.0
    else:
        result = sorted_list[round(length/2)]
    return result


#2

look at this code:

def median(_list):
    sorted_list = sorted(_list)
    result = 0
    length = len(sorted_list)
    if length % 2 == 0:
        mid_val1 = sorted_list[round(length/2)]
        mid_val2 = sorted_list[round((length/2)-1)]
        result = (mid_val1 + mid_val2)/2.0
    else:
        print round(length/2)
        result = sorted_list[round(length/2)]
    return result

print median([1])

as you can see, round will make the number 0.0, you don't need round, dividing two integers will just give a integer as result. (in python2 dividing two integers will floor the number)

VS might run python3, then you might need round, although i then would use floor, round is always a bit of a tricky thing


#3

Thank you! I remember your advice :smiley:


#4