Getting the median result as 5.0 instead of 4.5


#1
  1. Median
    def median(s):

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

    elif len(s) % 2!= 0:
    return s[(((len(s) +1) / 2)-1)]
    else:
    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??


Median
#2

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

s.sort()

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]

#4

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