Median - What is wrong with this code?


#1

I was working out with this for an hour and still I can't find what;s wrong.

def median (x_list) :
    n = 0
    a = len(x_list)
    x_list.sort()
    if a%2 == 0 :
        n = ((x_list[a/2] + (x_list[(a/2)-1]))/2)

    else :
       n = (x_list[a-1/2])
    return n

If I have a list with 4 contents, x_list[a/2] would be x_list[2] and x_list[(a/2)-1] would be x_list[1].

so It would be adding second and third largest from the list, since I've already sort it.

and all it says :

Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5

so I tried to fix the bug, and to check, I added some print thingi.

    n = 0
    a = len(x_list)
    x_list.sort()
    if a%2 == 0 :
        n = ((x_list[a/2] + (x_list[(a/2)-1]))/2)
        print x_list[a/2]
        print x_list[(a/2)-1]
        print x_list[(a/2)] + x_list[a/2-1]
        print (x_list[(a/2)] + x_list[a/2-1])/2
    else :
        n = (x_list[a-1/2])
    return n

median ([4,5,5,4])


5
4
9
4

and I gave up. Anybody knows what's wrong with my python saying 9/2 = 4?


#2

in Python 2.x

The operator / returns integer value if operands are integer.
To get float value(more precise value) we need to make one of the operand a float, You can use 2.0 instead of 2?


#3

Thanks for quick reply! solved the problem thanks to your help :slight_smile:


#4

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