Search code examples
pythonlistmedian

Take a list as an input and return the median value


Been stuck on this the last while and for the life of me can't find what's wrong. So the exercise in question is:

Write a function called median that takes a list as an input and returns the median value of the list. For example: median([1,1,2]) should return 1.

I'm doing this on codeacadamy and it keeps telling me the answer it's getting is 4 (should be 4.5 as the test list there using to check my code is [4,5,5,4]). To make things even weirder for me, I tried the code on a console IDE on the cscircles website (like how its feels) and that says its fine.

def median(y):
    x = sorted(y)
    x_len = len(x)
    if x_len % 2 == 0:
        start = x_len // 2
        median = (x[start-1] + x[start]) / 2
        return median
    else:
        start = x_len // 2
        median = x[start]
        return median

Solution

  • Cast as a float first. float((x[start-1] + x[start]))/2