Median


#1

Can anyone tell me why I'm getting this error message?
Thanks in advance!

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

Error:
'Oops, try again. median([6, 8, 12, 2, 23]) returned 6 instead of 8'

Code:

def median(nums):
    new = sorted(nums) 
    mid = len(new) / 2
    if len(new) % 2 == 0:
        x = (float(new[mid]) + float(new[mid -1])) / 2.0
        return x
    else:
        y = int(mid - 0.5)
        return new[y]

#2

the length of the list you have a problem with is 5, agree? So mid is 2 (5/2=2), which is the middle item. why are you doing: int(mid-0.5)? mid is already the middle item if the list contains a odd number of items, no need to do mid-0.5


#3

The 0.5 'logic' got me too, seems to work in theory but isn't correct.

I'll also add that float((a+b)/2) doesn't convert as you'd like. Using 2.0 is applicable. Guess its just the way its coded, as opposed to just getting to the correct answer. Pretty sure that's how the site works anywho.

Good luck :slight_smile: