# 15/15. Getting problem with even one

#1

I wrote up this code. This works fine with the odd number of items but can't function with even number of items.

``````def median(in_list):
median = 0
sorted_list = sorted(in_list)
count = len(sorted_list)
x = count / 2
if count % 2 == 0:
median = float((sorted_list[x] + sorted_list[x + 1]) / 2)
else:
median = (sorted_list[int(x + 0.5)])
return median
print median([4, 5, 5, 4])``````

I don't know why it cannot calculate the actual median. Any help will be good.

#2

Haven't looked through everything, but noticed a mistake here: median = float((sorted_list[x] + sorted_list[x + 1]) / 2)

Before you make it a float it's still an integer divided by another integer, which will result in an integer (so 4.5 becomes 4).

To fix this you can make the 2 a float by writing it as 2.0, instead of 2. That way you divide an integer by a float, which results in a float. That way you don't need to call the float function.

#3

But it is not giving the median as 4 instead it is showing 5... That's the reason i am confused
I have already tested ur suggestion but no change..

#4

You also made a mistake with indexing. Index starts at 0 rather than 1. So you'll need to get x and x-1, instead of x and x+1.

You also don't need the + 0.5 below. Since x is already an integer.

#5

Yeah now i got it... that was the mistake.. Thanks for the solution