Median


#1



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


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_item.sort()
   
    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]


#2

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

return float( ... ) / 2

Aside

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.


#3

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


#4

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


#5

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