Median - code not working


#1




Hello, can someone plz tell me what's wrong with my code because this code works fine on other IDEs. it's gives me the error below when i run it on codecademy.
Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5


def median(li):
    li=sorted(li)
    look=len(li)

    if look%2 != 0:
        life=look/2
        life=life+0.5
        life=life-1
        life=int(life)
        return li[life]
    else:
        life=look/2
        lo=life-1
        lo=int(lo)
        life=int(life)
        lok=li[life] + li[lo]
        lok=lok/2 
        return lok


#3

i just explained this difference here:

It should also answer your question


#4

thanks for the reply, but what part of the code do i modify? and how? converting to float?


#5

i figured it out.. but what other things were modified in python 3 so that i can be aware.

def median(li):
    li=sorted(li)
    look=len(li)
    
    if look==1:
        return 1

    elif look%2 != 0:
        life=look/2
        life=life+0.5
        #life=life-1
        life=int(life)
        return li[life]
    else:
        life=look/2
        lo=life-1
        #lo=int(lo)
        #life=life
        lok=li[life] + li[lo]
        lok=float(lok)
        lok=lok/2
     
        
    return lok

#6

here is a whole list:

print "hello world" vs print("hello world")
most important: raw_input() is now input() python3

some methods are changed dictionary items vs iteritems

I am sure there is more, division was changed as you know :wink:


#8

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