# 15. Median

#1

Can someone help me with my code?
def median(num_list):
sort = sorted(num_list)
length = len(sort)
if length % 2 != 0: #odd number list
a = length / 2
return sort[a]

``````elif length == 0: #even number list
b = length / 2
c = b - 1
d= (sort[b] + sort[c]) / 2
return d``````

I get an error saying that median([4, 5, 5, 4)] returned None, did you remember to return a result?
But I did return result d in the last line.

#2

Can you add backticks before and after the code, so it's formatted like a code block? That way everyone can see the indentation and other formatting.

`````````

#3

You forgot the modulo part here.

#4

def median(num_list):
sort = sorted(num_list)
length = len(sort)
if length % 2 != 0: #odd number list
a = length / 2
return sort[a]

``````elif length % 2 == 0: #even number list
b = length / 2
c = b - 1
d= (sort[b] + sort[c]) / 2
return d``````

The error is now that: Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5

#5

'''def median(num_list):
sort = sorted(num_list)
length = len(sort)
if length % 2 != 0: #odd number list
a = length / 2
return sort[a]

``````elif length % 2 == 0: #even number list
b = length / 2
c = b - 1
d= (sort[b] + sort[c]) / 2
return d'''``````

#6

I think that if you divide one integer by another you will always get out an integer.

Try `d= (sort[b] + sort[c]) / 2.0)` instead. This way the division will evaluate to a float.

#7

I'm sorry. I tried:
def median(num_list):
sort = sorted(num_list)
length = len(sort)
if length % 2 != 0:
a = length / 2
return sort[a]

``````elif length % 2 == 0:
b = length / 2
c = b - 1
d = (sort[b] + sort[c]) / 2
return d``````

I typed it out, hope that helps!

#8

Thank you!!!!!! It worked with changing it to 2.0.

#9

I don't know if it helps but sometimes a different view is quite refreshing for the mind. Anyways here my solution:

`def median(lst): lst = sorted(lst) if len(lst) % 2 != 0: return lst[len(lst)/2] else: return (lst[len(lst)/2] + lst[(len(lst)/2)-1]) / 2.0`