Median


#1


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


I expected the code to execute the else statement which should return 4.5.
I know the code is roundabout comparative to others I have looked at in this thread, but I just want to understand where the breakdown is in this logic.
Thanks for the help


def median(x):
    new_x = sorted(x)
    middle = len(new_x) / 2
    middle_add1 = (len(new_x) / 2) + 1
    if len(new_x) == 1:
        return new_x[0]
    elif len(new_x) % 2 != 0: # means input length is ood
        m = float(new_x[middle])
        m1 = float(new_x[middle_add1])
        return new_x[int(middle + .5)]
    else:
        m = float(new_x[middle])
        m1 = float(new_x[middle_add1])
        return (m + m1) / 2
print median([4,5,5,4])


#2

Recall that because of zero-indexing,

n = int(len(x) / 2)

is the middle index of an odd length list, and the upper-middle index in an even length list.

Say we have a list containing 8 values.

n = int(8 / 2)    # 4

0  1  2  3  4  5  6  7
            ^
       upper middle

This means the lower middle index will be n - 1.

Remember to convert to float:

return float(x[n - 1] + x[n]) / 2

#3

Thanks for your help! Solved the problem right away.


#4