15. median


#1

EDIT: I got it! Needed to set num_list as sorted list.

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

Error:
Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5

I don't think the sorted function is working correctly, not sure if I implemented that wrong. But if I add 2 more numbers to the end of the list it will return 4.5, which is the average of the 4 and 5 that would then be the middle of the list.

def median(num_list):
    sorted(num_list)
    pos1 = len(num_list) / 2
    pos2 = pos1 - 1
    if len(num_list) % 2 == 0:
        return float(num_list[pos1]+num_list[pos2])/2
        
    else:
        return float(num_list[pos1])
print median([4,5,5,4])


#2

here:

sorted(num_list)

you sort the list, but don't store the sorted list anywhere?


#3

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