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

def median(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


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.


the problem is here:


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


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