in the fifteenth paragraph of Practice Makes Perfect
i need to find medium value.
I was faced with the following error :Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5

But why!?

length of List is 4, in this way function must return medium value for 5 and 5. and it's 5!

my code

def median(L):
    if len(L)%2==0:
        med = L[(len(L)-1)/2]
    return (med)


Check the definition for median as it applies to statistical analysis. The sample space is always sorted and the middle value or average of the middle two values is the median.


def median(lst):
lst_sort = sorted(lst)
count = (len(lst))
a = count/2
b = 0
if count == 1:
return lst_sort[0]
elif count%2 == 0:
b = lst_sort[a-1]
a = lst_sort[a]
return (a + b)/2.0
else :
return lst_sort[a]

this worked well, it incorporates a float on even numbers with the ((a+b)/2.0) but when odd will simply divide the count by two and round down to find the index number.


This uses implicit typing on the denominator (a counting number) which is a form of fudging to make one's code work. Better, in my opinion that we use explicit typing on the numerator, and leave the denominator as a counting number (the integer that it is).