# Median problem

#1

Oops, try again. median([4, 5, 5, 4]) returned 4.0 instead of 4.5

I even printed each value to the screen in this situation. For an even amount of numbers ( like in [4, 4, 5, 5]) after sorted show 5 as 'first', 4 as 'second' and 9 as 'a', which is the sum of the two....but when i divide that by 2, it returns 4 instead of 4.5?

``````def median(numbs):
#sort list
new_list = sorted(numbs)
# if list has even amount of numbers
if len(new_list) % 2 == 0:
print new_list #[4, 4, 5, 5]
print len(new_list) #4
second = new_list[(len(new_list) /2)] #Get right middle number in list
print second, 'second' #5
first = new_list[(len(new_list) / 2) - 1] #get left middle number in list
print first, 'first' #4
a = first + second #9

#?????
med = (float(a / 2))
print a, 'first + second'
print med, 'med'
return med
elif len(new_list) == 1:
med = new_list[0]
else:
middle_index = (len(new_list) + 1) / 2
med = new_list[middle_index]
return med

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

#2

Integer division results in an integer (and converting it to float afterwards doesn't recover the lost precision.. it's not there, nothing to recover)

#3

Got it! Thank you so much. I was on such a roll knocking out these exercises then I just couldn't figure out why it wasn't returning a float.

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.