Median


#1

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

Grrr.... Not sure why it is not working.

def median(x):
    result = 0
    for n in sorted(x):
        if len(x) % 2 == 0:
            result = (x[len(x)/2] + x[len(x)/2 - 1]) / 2.0
        else:
            result = x[len(x)/2]
    return result


#2

Hi @aviss ,

See the documentation on the Python sorted function.

After you call the function, you have accessed x. But has x actually been sorted? You can test it by printing it.


#3

I thought I sorted it in line 3 - for n in sorted(x): But it probably does work like this... I introduced a new list (sorted) and the code works now! Thanks! Will read more about sort().


#4

Hi, @aviss,

Also note that you do not need the for loop. That loop visits every index in the list, but to compute the median after the list has been sorted, you only need to access the one or two middle items in the list.


#5

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