Median code compiles with different results


#1


I get wrong results when I run this code in code academy but the right result in skulpt.org
What is going on?



def median(arr):
    sorted(arr)
    length = len(arr)
    alength = len(arr) - 1
    medval = 0.0
    if length % 2 == 0:
        medval = float((arr[int(round(alength/2))] + arr[int(round(alength/2)) - 1]) / 2.0)
    else:
        medval = arr[int(alength/2) - 1]
    
    return medval
    
arr = [0,1,1,6,8,34]
print median(arr)


#2

adding a print statement is revealing:

def median(arr):
    sorted(arr)
    length = len(arr)
    alength = len(arr) - 1
    medval = 0.0
    if length % 2 == 0:
        print int(round(alength/2))
        medval = float((arr[int(round(alength/2))] + arr[int(round(alength/2)) - 1]) / 2.0)
    else:
        medval = arr[int(alength/2) - 1]
    return medval
    
arr = [0,1,1,6,8,34]
print median(arr)

if you run this both on codecademy and trinket, you will see codecademy gives (and my python too) prints 2, while trinket prints 3. This problem is explained here

Round can be really tricky and risky.


#3

Ok thanks mate. I 'll figure another way to do it. It seems though I am on the right track.