Error in median


#1



returning 4.0 instead of 4.5


Replace this line with your code. 
def median(r):
    r=sorted(r)
    t=len(r)
    if t%2==0:
        p=(t/2)
        q=(t/2)-1
        s=float((r[p]+r[q])/2)
        return s
    
    else:
        if t==1:
            return r[t-1]
        else:
            p=(t+1)/2
            return r[p]


#2

float() is incorrectly used, the division (9/2) happens first, causing the number to floor, and then cast to a float.


#3

You have to change correct this two lines.

s=float((r[p]+r[q])/2) to s=(r[p]+r[q])/2.0

and

return r[p] to return r[p - 1]


#4

still returning 4 instead of 4.5


#5

i covered this problem. How do you think you can solve it?


#6

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