Practice Makes Perfect 15/15

#1

Here is my code:

``````def median(num):
num = sorted(num)
md = len(num)/2
if len(num) == 1:
return num[0]
elif num%2 == 0:
return num[md]
else:
return (num[md-1] + num[md+1])/2``````

#2

Hello

The problem is in this line:

``elif num%2 == 0:``

Your script tries to perform a modulo (`%`) operation on the list. We can't divide a list by an integer, right?

You want to check if the length of the list is even, not the list itself Use `len` function.

#3

still getting the error after using len function

this is my code:
def median(num):
num = sorted(num)
md = len(num)/2
if len(num) == 1:
return num[0]
elif len(num)%2 == 0:
return num[md]
else:
return (num[md-1] + num[md+1])/2

#4

Firstly, I believe there is still a problem in this line:

I believe it should be 1 instead of 0.
Secondly, in the final line, you need to use num[md], instead of num[md+1].
Finally, you need to divide by 2.0

#5

another way to do it:

``````def median(l):
ns = sorted(l)
lns = len(ns)
med=float((ns[(lns-1)/2]+ns[lns/2]))/2
return med

print median([1,2,3,4,3,2,4,5,6,7,3,2,3])``````

#6

``````def median(x):
x.sort()
if len(x)%2==0:
med=((x[len(x)/2])+x[len(x)/2-1])/2.0
else:
med=x[int(len(x)/2+0.5)]
return med

print median([1,7,2,3,9,5,4,11])``````

this code is simple and works