15/15: What is wrong with this code?


#1

It returns 5.0 instead of 4.5 when [4,5,5,4] goes in. You cannot take the int()s out because then it'll say you cannot use floats as indices of a list.


#3

Let's see if we can reduce this to a simple algorithm:

def median(n):
    n.sort()
    j = len(n)/2.
    k = int(j)
    if j == k:
        m = (n[k] + n[k-1])/2.
    else:
        m = n[k]
    return m

print median([4,5,5,4])     # 4.5

It is another thing altogether to attempt to access the array elements by their median, since in even count arrays, the median is a float, and not necessarily a value in the array. We can use midpoint arithmetic to zero in on the two middle elements, which is easy enough to reason out.