Getting the median result as 5.0 instead of 4.5

  1. Median
    def median(s):

    if len(s) == 1:
    return s[0]

    elif len(s) % 2!= 0:
    return s[(((len(s) +1) / 2)-1)]
    return (s[(len(s)/2)-1] +s[len(s)/2])/2.0

I am getting the median result as 5.0 instead of 4.5 for the list [4,5,5,4]
What cud be the possible error??


That function is not in-place. To do an in-place sort, use the method.


The length of the list only becomes a question for the purpose of determining parity; and, for finding the middle element. If the length is only 1, it will come out in the wash.

n = len(sample)
# pretend n is 1
m = int(n / 2)    #  0

return sample[m]


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