Got answer, but need clarification


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096#


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
    else:
        return xsort[len(xsort) / 2]


#2

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


#3

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