Median


#1



median([4, 5, 5, 4]) returned 5 instead of 4.5 , I think I am misusing the sorted function.


def median(numbers):
    sort=sorted(numbers)
    a= int((len(sort)/2)+.5) #for a list with an odd number of elements a= the middle element.
    if len(sort)%2!=0: # if the list is odd
        return sort[a] #return middle value
    else:    #if list is even
        x=len(sort)/2 # x is the lower of the two middle terms
    
        answer=(sort[x]+sort[x+1])/2 #average the two middle terms
        return answer


#2

I realize now that my list starts at index 0 so I need to subtract 1 when I use list indices. However even when I make this change I get the same error.


#3

the problem is here:

answer=(sort[x]+sort[x+1])/2

agree with me that if we do the math for [4,4,5,5] it would like this:

(5 + 4) /2

so 9/2, which 4. a integer (non decimal number) divided by a integer gives a integer in return, either divide by a float (2.0 for example) or use float() to cast it to a float


#4

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