Median


#1



Median


I keep getting the error that list indices should be integers and not floats. I don't know what I'm going wrong here. Can someone help me out?


Replace this line with your code. 
def median(nums):
    if len(nums) > 1:
        nums = sorted(nums)
        if len(nums) % 2 == 0:
            middle = len(nums)/2.0
            result = (nums[middle] + nums[middle - 1])/2.0
            return result
        else:
            result  = nums[(len(nums) + 1)/2.0]
            return result
    else:
        return nums[0]


#2

here:

middle = len(nums)/2.0

because you use 2.0, middle will be a float. Indexes should be integers, not floats


#3

I changed that 2.0 to 2, but I'm still getting the same error. when I try changing the other 2.0, it tells me that the answer is not correct anymore.


#4

think careful where you use 2 and 2.0, when you need float (result) and integer (index), like here:

result  = nums[(len(nums) + 1)/2.0]

you need an index, so you should use 2

also, length / 2 gives the middle value, not sure why you add +1


#5

Ah I understand now. thanks for the help!


#6