15/15 - list index out of range


#1

Tried to look at other forums but not quite sure what I have done with my code!
Any help explaining what I have done? I am given the error message "median([1]) resulted in an error: list index out of range"

My code is:

def median(numbers)
numbers=sorted(numbers)
count=len(numbers)
if count % 2 != 0:
return numbers [count % 2]
else:
num1 = numbers [(count-1) %2]
num2 = numbers [(count) %2]
return (num1+num2) % 2

Thanks!


#2

There's a couple of things:

(1) When you said count %2, I think you meant count / 2. Same thing for the next 3 usages of %.

What was happening was, for a list of length 1, 1%2=1, but numbers[1] does not exist if numbers=[7], etc.

(2) In calculating num1 and num2, you need to drop any decimal, for instance by using the int function

(3) In the return statement, you need to divide by 2.0, or else the integer arithmetic division gives the wrong answer.

Here it is fixed:

def median(numbers):
numbers=sorted(numbers)
count=len(numbers)
if count % 2 != 0:
return numbers [count / 2]
else:
num1 = numbers [int((count-1) /2)]
num2 = numbers [int((count /2))]
return (num1+num2) / 2.0;

print(median([1,2,3,4,5,6]))