Median


#1



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


Oops, try again. median([4, 5, 5, 4]) resulted in an error: list indices must be integers, not float


Anyone know what's wrong in my code?


def median(lst):
    lst1 = sorted(lst)
    if len(lst1) == 1.0:
        return (lst1[0])
    elif len(lst1) % 2.0 == 0:
        med1 = lst1[(len(lst1) / 2.0)]
        med2 = lst1[(len(lst1) / 2.0) - 1.0]
        med = (med1 + med2) / 2.0
        return med
    elif len(lst1) % 2.0 == 1.0:
        med = (lst1[(len(lst1) / 2.0) + 0.5])
        return med


#2

This is a float:

lst1[ ___(len(lst1) / 2.0)___]

#3

so if i use the int function on them, would that make it okay?


#4

Yes, that will work. But also, don't divide by a float.

len(lst) / 2

will return an integer in Python 2 (these lessons)

int(len(lst) / 2)

will give an explicit integer (required in Python 3).


#6

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