Median function works in python but not here?


#1

Why doesn't my code work here but does in python IDE?

def median(a_list):
    A = sorted(a_list)
    #Even number must take the average of the two middle numbers
    
    if len(a_list) % 2 == 0:
        b = (len(A)) // 2
        median_is_even = ( (A[(b)]) + (A[b-1]) ) / 2
        return median_is_even
    
    #Odd number list will have only one number in the middle
    else:
        c = (len(A))//2
        median_is_odd = a_list[c]
        return median_is_odd


#2

because your IDLE very likely runs python3, in your IDLE:

9 / 2 = 4.5

on codecademy, python2:

9 / 2 = 4

fundamental changes where made in python3 on how division works. To overcome this problem, try using float() or divide by a float (2.0 is the same as 2)


#3

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