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

I don't know where I am getting error the code seem right i have tested it with Idle and it works fine. it's bugging me please help

 def median(list_item):
    list_length = len(list_item)
    if list_length%2 == 0:
        median = list_length//2
        return (list_item[median - 1] + list_item[median])/2
        #return median_value
    elif list_length%2 == 1:
        median = list_length//2
        return list_item[median]


Tack on float to the front of that and it will return a float value.

return float( ... ) / 2


If I may interject.... median - 1 is a wee bit misleading. Median is not an index, but the middle value in a sorted list. We should not use the terms interchangeably. They are not synonymous and not interchangeable.

middle would be a more suitable variable since it actually describes its role, or like I always use, m

m = int(n / 2)

where n is the length of the list.

Your code says that that is what you meant, so I'm not knocking that, only making sure we are on the same page, semantically, from a reader's perspective.


Alright thanks. introducing the float work. I'll make necessary adjustment.


A post was split to a new topic: Practice makes perfect - Median


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