15. Issues with error message in median


#1



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


Well, honestly I think I'm in the wrong but this error message doesn't help me, it says "Oops, try again. median([4, 5, 5, 4]) returned 5 instead of 4.5"


So, following the rules of the exercise, if the list contains an even number of elements (in this case four), you should take the two middle ones (5,5) and average them (5+5 equals 10, 10/2 equals 5; 5 is the median)


def median (numList):
    workList=sorted(numList)
    #if it's even
    if len(numList)%2==0:
        average=(workList[len(workList)/2]+\
        (workList[len(workList)/2])+1)/2
        return average
    else:
        #print (len(workList)+1)/2
        return workList[((len(workList)+1)/2)-1]
#median([1])


#2

average needs to be a float.

float( x[n - 1] + x[n] ) / 2

#3

You're right, plus, I had my indexes wrong, I began counting from 1


#4

( x[n - 1] + x[n] ) / 2.0
another way to make float


#5

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