15/15 Median- why is this code giving a syntax error?


#1

def median(n):
n = sorted(n)
first = n[len(n)/2-1]
second = n[len(n)/2]
if len(n)%2:
return m = (first + second)/2.0
else:
return m = n[len(n)/2.0 - 0.5]

Why is this code giving a syntax error?


#2

Which Lesson Would This Be In?


#3

practice makes perfect. But the problem is solved with the code above.

I also had syntax error with the code below-

def median(n):
n = sorted(n)
if len(n)%2:
return m = (n[len(n)/2-1] + n[len(n)/2])/2.0
else:
return m = n[len(n)/2.0 - 0.5]


#4

Here is my solution. You will notice I have some additional lines. They are just to check whether the code is correct.

def median(seq):
new_list = sorted(seq)
print new_list
print len(new_list)

    if len(new_list) == 1:
        return new_list[0]
    elif len(new_list) % 2 != 0:
        m = int(len(new_list) * 0.5 - 0.5)
        return new_list[m]
    else:
        first = ((len(new_list))/2) - 1
        second = (len(new_list))/2
        print first, second
        a = (new_list[first])
        b = (new_list[second])
        print a, b
        median = (a+b) * 0.5
        return median

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

Let me know if there are any questions.

Enjoy))