Median returning 4 not 4.5


I don't know what's going on here. I believe I am averaging the correct numbers here.

def median(sequence):
sequence = sorted(sequence)
if len(sequence) % 2 == 1:
i = float(len(sequence))
j = i/2 - 0.5
j = int(j)
return sequence[j]
i = (len(sequence)/2)
j = i - 1
s = sequence[i] + sequence[j]
return s/2


Let's start by examining this line...

Why would we take a perfectly good integer and convert it to a float? It is a counting number, why not just leave it that way?

m = len(sequence)

The number to declare as a float is the numerator. The quotient will continue to be a float and the division will make perfect sense.

In the present sense, we don't want a float until the return value is prepared. What we need is an integer value for the median index of a odd length list.

n = int(m / 2)

Recall that lists a zero-indexed, so if we look at an odd length list,

x = [ 2, 4, 6, 8, 10 ]
          x[n]  where  n = int(5 / 2) = 2

median = x[n]

For an even length list the median is the middle two terms averaged. Notice that x[n] is still in the middle, but on the right side (lowest value of upper half). The left side will be x[n - 1], the highest value of the lower half.

This is where the float() comes in.

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


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