15/15 Median


#1

def median(alist):
    alist = sorted(alist)
    length = len(alist)
    if length % 2 == 0:
        medians = 1
        medians = medians * alist[length / 2]
        medians = medians * alist[length / 2 - 1]
        medians = medians / 2
        return medians
    else:
        print alist
        return alist[length / 2 - 1]

I get this error :median([4, 5, 5, 4]) returned 10 instead of 4.5

Not sure how it got that result. Can I get some advise?


#2

iirc this is addressed in the last part of the hint in the exercise. you're supposed to divide by 2.0 to get a "float" which i'm not sure what the exact definition is but it includes decimals, instead of dividing by 2 which just gives you an integer (whole number. i guess it rounds the answer)


#3
def median(num):
    n = len(num)
    num = sorted(num)
    if n%2 == 1:
        m = n/2
        #print m
        s=  num[m]
        #print s
        return s
    else:
        m = n/2
        #print m
        s = float ((num[m-1] + num[m]))/2
        #print s
        return s
num = [1, 2, 3, 4, 5]
median(num)

this one works fine. but in your code u reassigned the medians twice


#4

instead of using medians = medians * alist[length / 2 - 1] use this medians = medians + alist[length / 2 - 1] and also return in else alist[length /2]


#5

Hi @joseph_newbrough,

  1. The last statement should not be doing - 1
  2. In the code:

medians = 1
medians = medians * alist[length / 2]
medians = medians * alist[length / 2 - 1]
medians = medians / 2

Why are you doing medians = 1 on line 1? Then, when you perform line 3, you overwrite the value stored on line 2. You will want to add that value to medians. And, you need to divide by 2.0 to obtain accurate decimal result.

If you are confused, let me know.