Median troubles


It's throwing me an error saying that my function is returning 4 instead of 4.5 for this example: median([4, 5, 5, 4])

I expected a 4.5 because I backtested this in an IDE and it gave me back the correct answer.

def median(array):
    newArray = sorted(array)
    if len(newArray) % 2 == 0:
        number = len(newArray)/2
        number = int(number)
        sum = newArray[number - 1] + newArray[number]
        quotient = sum/2
        return quotient
        number = (len(newArray) - 1)/2
        number = int(number)
        return newArray[number]


I found the problem! I just changed my code to

quotient = sum/2.0

and it worked perfectly! Sorry for the post mess up!


This is one way to declare a float, but it looks contrived. 2 is an integer so it should be left as an integer. Better to explicitly declare the float in the numerator.

float(sum) / 2

To your reader this will make perfect sense, since it is semantically correct.

Something about Python 2... When we divide an integer by an integer, the return is an integer (rounded down to floor). Technically, this line is not needed...

    number = int(number)

since number is an integer in this case.

This looks a little like fudging, manipulating the data to give a correct result. Given that Python 2 returns an integer, the - 1 part is not needed.

Consider declaring three working values at the start of the program. These will apply in both branches.

o = sorted list
n = len(o)
m = int(n / 2)

Now in your branches,

if n % 2:    # odd
    return o[m]
    return float(o[m - 1] + o[m]) / 2

I've used shortened variables for simplicity.:


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