Median


#1



My code for the median exercise gives the following error message.

median([4, 5, 5, 4]) resulted in an error: list index out of range


I don't know what the actual error is, or how to fix it. Any help would be greatly appreciated.


def median(numbers):
    numbers.sort()

    if len(numbers) == 1:
        med = numbers[0]

    if len(numbers) % 2 == 0:
        first = numbers[(len(numbers)/2)]
        second = numbers[(first-1)]
        med = (first+second)/2
  
    else:
        reduced = len(numbers) - 1
        med = numbers[(reduced/2)]
   
    return med


#2

I added a function call + print statement to your code:

def median(numbers):
    numbers.sort()

    if len(numbers) == 1:
        med = numbers[0]

    if len(numbers) % 2 == 0:
        first = numbers[(len(numbers)/2)]
        print first
        second = numbers[(first-1)]
        med = (first+second)/2
  
    else:
        reduced = len(numbers) - 1
        med = numbers[(reduced/2)]
   
    return med
print median([4, 5, 5, 4])

as we can see from this code, first contains the number stored (5), which is fine, but this means you can't do this:

second = numbers[(first-1)]

since first holds the number at that index, not the index itself. You would need to do:

second = numbers[(len(numbers)/2-1)]

This should resolve your current issue, if you need more help, let me know (but i recommend to try it yourself first)


#3

The error message is now this:

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

The code I am now running looks like this:

def median(numbers):
numbers.sort()

if len(numbers) == 1:
    med = numbers[0]

if len(numbers) % 2 == 0:
    first = numbers[(len(numbers)/2)]
    print first
    second = numbers[((len(numbers)/2)-1)]
    med = (first+second)/2

else:
    reduced = len(numbers) - 1
    med = numbers[(reduced/2)]

return med

print median([4, 5, 5, 4])


Median
#4

Have you tried to sort out what the problem is? The problem is in this line:

med = (first+second)/2

first and second are both integers (5 and 4), divide by a integer gives a integer (the number get floored), to overcome this problem divide by a float, or cast the outcome to a float using float()


#5

3 posts were split to a new topic: 15. median


#8

A post was split to a new topic: Median