15 median!


#1



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

Hello, I have an error message for the code below, what should I fix?
Text of the error: "median([1]) resulted in an error: 'int' object has no attribute 'getitem'"


def median(deflist):
    sortedlist = sorted(deflist)
    counter = 0
    for item in sortedlist:
        if len(sortedlist)%2 == 0:
            counter = (item[(len(sortedlist)-1)/2] + item[(len(sortedlist)-1)/2 + 1])/2.0
        else:
            counter = item[len(sortedlist)/2]
    return counter


#2

What happens when we cache this in a simple variable?

m = len(sortedlist)

...

    if m % 2 == 0:
        counter = (item[(m - 1) / 2] + item[(m -1) / 2 + 1]) / 2.0
    else:
        counter = item[m / 2]

Now we can turn our focus to the line that is most likely to contain logic or math errors.

We know that m is the length, namely the 'sample space'. We know also that the samples are sorted. In an even number of samples, we average the middle two data points. Say we have a sample space of eight data points.

8 / 2  =>  4

The middle two terms then are at index [4-1] and [4].

counter = (item[m / 2 - 1] + item[m / 2]) / 2.0