Median. List index out of range


#1



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

Whenever I run it it gives me the error median([4, 5, 5, 4]) resulted in an error: list index out of range

What am I doing wrong and how do I fix it?


def median(nums):
    nums = sorted(nums)
    median = nums[nums[len(nums)-1] / 2]
    if len(nums) % 2 == 0:
        med_1 = median
        med_2 = nums[median-1]
        median = (med_1 + med_2) / 2.0
        return median
    else:
        return median


#2

here:

med_1 = median

what are you doing here? median is your function, shouldn't this be the index?


#3

I just changed that, but it's still giving me the same error.
Here's what i changed it too:

def median(nums):
    nums = sorted(nums)
    med = nums[nums[len(nums)-1] / 2]
    if len(nums) % 2 == 0:
        med_2 = nums[med-1]
        med = (med + med_2) / 2.0
        return med
    else:
        return med

#4

now med doesn't contain an index, which is fine, but then you have to calculate med_2 (not using med)

please think about the logic of your code


#6

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