[Solved] 15/15 median - (5+4)/2 = 4.0 instead of 4.5?


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096


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


I don't get why float((5+4)/2) returns 4.0 instead of 4.5, it works with other lists but not this one.

Code is:
[Extra 'print' statements have been added for debugging purposes, here commented out for readability]

nums1 = [2, 3, 4, 5, 6] #test list one
nums2 = [15, 12, 27, 55, 32, 10] #test list two

def median(argument): #expect a list of numbers
#    print argument
    nums = sorted(argument)
#    print nums
    x = int(len(nums)/2)
#    print "len/2 = ", x
    if len(nums) % 2 == 0:
#        print "list len is even:", nums[x], nums[x-1]
        return float((nums[x] + nums[x-1])/2)
    else:
#        print "list len is uneven:"
        return nums[x]

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

The prompt says:

[2, 3, 4, 5, 6]
[2, 3, 4, 5, 6]
len/2 = 2
list len is uneven:
4
[15, 12, 27, 55, 32, 10]
[10, 12, 15, 27, 32, 55]
len/2 = 3
list len is even: 27 15
21.0
[4, 5, 5, 4]
[4, 4, 5, 5]
len/2 = 2
list len is even: 5 4
4.0
None

I don't get what's going on here, any help wil be apreciated :slight_smile:
I even tried this:

temp = nums[x] + nums[x-1]
#        print temp
        return float(temp/2)

but still:

[4, 5, 5, 4]
[4, 4, 5, 5]
len/2 = 2
list len is even: 5 4
9
4


#2

((nums[x] + nums[x-1])/2) this evaluates to an int. If you put float around it, all you are getting is somthing like 3.0 instead of 3.5. I usually just did

return (nums[x] + nums[x-1])/2.0

edit: missed a bracket oops


#3

Now I get it:
I was turning into float something which was calculated while still an int.
Using

(nums[x] + nums[x-1])/2.0

moved the step of 'float-ing' back into the work code.
Also, I suppose that:

float(nums[x] + nums[x-1]) / 2

(although less elegant) would have worked too, as I am turning "9" into "9.0" before the division takes place, is it right?

Thank you!


#4

That's correct. You can also do

float(nums[x] + nums[x-1]) / 2

:slight_smile:


#5

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