Median


#1



median

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


im not sure why this code doesn't work. ive been doing this for a while and my eyes aren't seeing anything. can anybody point me in the right direction?


def median(s):
    s = sorted(s)
    a = len(s)
    if a % 2 == 0:
        # return average of middle two numbers
        b = (a - 1) / 2
        c = (b - 1)
        d = (s[b] + s[c]) / 2.0
        return d
    else:
        b = (a - 1) / 2
        return s[b]
    
    
print median([4, 5, 5, 4])


#2

if we have the following list:

[4, 5, 5, 4]

we have the following data: a length of 4, and indexes: 0, 1, 2 and 3

b contains 0, and c contains 1, this are not the middle indexes


#3

The middle of two numbers in a zero-indexed, even length list are,

m = int(len(x) / 2)

and,

m - 1

so that,

float(x[m - 1] + x[m]) / 2

will be the median of a sorted list.


#4

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