Got answer, but need clarification


The code works fine. I almost came up with the solution on my on, but became frustrated when I couldn't get it to work, so I checked the forums. What I was doing wrong was my parentheses and brackets. However, I still don't really understand why these items had to be placed in this order. could someone please explain, in layman's terms?

Also, for return (xsort[a] + xsort[b]) / 2.0, why did I have to put xsort[a] and xsort[b]? Why can't you just put return (a + b) / 2.0? Thanks.

def median(array):
    xsort = sorted(array)
    if len(xsort) % 2 == 0:
        a = len(xsort) / 2
        b = (len(xsort) / 2) - 1
        return (xsort[a] + xsort[b]) / 2.0
        return xsort[len(xsort) / 2]


a and b are indexes, not the values in their respective elements.


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