15/15 Median What is wrong with my code?


#1

def median(l):
sorted(l)
if len(l)%2==0:
x=(len(l)/2)
y=(len(l)/2)+1
return (l[x]+l[y])/2.0

else:
    x=len(l)/2
    return l[x]

I have sort the list before beginning the 'if' condition, but it still gives me the error:
Oops, try again. median([6, 8, 12, 2, 23]) returned 12 instead of 8


#2

I had the same problem as you do and when I checked out your post I realized that I , as you did, sorted x but that doesn't mean that the input list changed, in the for loop the former I is usef. You just have to create a new list that has as items the items of I in a sorted way( new_list=sorted(I) )


#3

I changed the line " y=(len(l)/2)+1" to "y = (len(l) / 2) - 1" and it went through.


#4

Since we are passing this function a list object, we can narrow down the sort to a list sort:

def median(lst):
    lst.sort()        # sort list in place
    x = len(lst) / 2  # x will be integer

We can see why you had to change y to be x - 1 since an even count will give the index of the right-side element of the median pairing. The left-side element is at index of the right-side minus 1. Which gives us this...

    return lst[x] if x % 2 else (lst[x] + lst[x-1]) / 2.0