I can't get it! What's wrong with it?


#1

I know the odd part is OK, but even pert......

def median(alist):
    n = sorted(alist)
    for i in n:
        if len(alist)%2 ==1:
            return n[len(alist)/2]
        else:
            a=alist[(len(alist)/2)]
            b=alist[(len(alist)/2)-1]
            ans=(a+b)/2.0
            return ans

#2

Not sure we need a loop to solve this one. Let's review:

n = [ 2, 5, 9, 3, 7, 6, 8 ]
n.sort()
j = len(lst) / 2
k = int(j)

In the above, an odd length list, j will be a float. k will be its integer or whole number component, so we know that k < j IF j is a float.

Add one more element to the list and the length will be even. The above simple arithmetic returns j and k but both will be equal. So that's our decision maker number one... Which approach do we use?

IF j does not equal k then we know that element k is the median, otherwise we must query the two elements k and k-1, then take their average.

if j == k:
    m = (n[k] + n[k-1]) / 2.
else:
    m = n[k]
return m

#3

Example:

n = [ 2, 5, 9, 3, 7, 6, 8 ]
n.sort()
print n                     # [ 2, 3, 5, 6, 7, 8, 9 ]
j = len(n)
print j                     # 7
j /= 2
print j                     # 3.5
k = int(j)
print k                     # 3

Since k < j,

# [ 2, 3, 5, 6, 7, 8, 9 ]
#            ^
#            |
#         index 3

The median, then, is 6.

n = [ 2, 8, 5, 9, 3, 7, 6, 8 ]
n.sort()
print n                         # [ 2, 3, 5, 6, 7, 8, 8, 9 ]
j = len(n)
print j                         # 8
j /= 2
print j                         # 4
k = int(j)
print k                         # 4

Since j == k,

# [ 2, 3, 5, 6, 7, 8, 8, 9 ]
#            ^  ^
#            |  |__
#            |      index 4 (k==4)
#         index 3 (k - 1)

So the median, then, is

m = (n[4] + n[3]) / 2.          # (7 + 6) / 2. => 13 / 2.
print m                         # 6.5

For the record, dividing by a float yields a float. n / 2. is a Python shortcut.