15.15 (median) cannot sort properly


#1



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


Error: median([4, 5, 5, 4]) returned 5 instead of 4.5


Can anyone tell me why it happens? Did I sort the list wrongly?
Thank you.


def median(sequence):
    new_list = sorted(sequence)
    n = len(new_list)
    if n % 2 == 0:
        return (new_list[n / 2] + new_list[(n / 2) - 1] )/2
    else:
        n % 2 != 0
        return new_list[int(n/2)]


#2

the sorting seems to be fine:

def median(sequence):
    new_list = sorted(sequence)
    print new_list
    n = len(new_list)
    if n % 2 == 0:
        return (new_list[n / 2] + new_list[(n / 2) - 1] )/2
    else:
        n % 2 != 0
        return new_list[int(n/2)]
print median([4,5,5,4])

the problem is that a integer divided by a integer returns a integer. use float() or divide by a float (2.0) when the list has a even number of items


#3

def median(sequence):
    new_list = sorted(sequence)
    n = len(new_list)
    if n % 2 == 0:
        return (new_list[n / 2] + new_list[(n / 2) + 1] )/float(2)
    else:
        n % 2 != 0
        return new_list[int(n/2)]

I tried to do this, but it still return the same thing. But I still don't know why?:joy:


#4

the lists sorts fine, but you changed this bit:

new_list[(n / 2) - 1]

you changed the - to a +, so now if the list has 4 items, the length is 2, so 2 + 1 you have index 2 and 3 (the two most right items), change it back to a -


#5

Thank you! I've understood ald!


#6