15/15 median: "List Index out of range" Error


#1

So i feel like the code is correct, but apparently the list index is out of range.

def median(x):
  l = sorted(x)
  n = len(l)
  answer = 0
  if n % 2 != 1:
    answer = ((l[(n/2)]) + (l[(n+2)/2])) / 2
    return answer
  else:
    answer = l[(n+1)/2]
    return answer

#2

here:

answer = ((l[(n/2)]) + (l[(n+2)/2])) / 2

why n+2? if the list has a length of 4, then then n+2 is 6. A list with 4 items has 3 as highest index


#3

If we assume list length is 4, then the calculation would be (4+2)/2 = 3.

I’m guessing it’s not doing the calculation correctly so the index is out of range as you said.


#4

but if the list has a length of 4, 4 / 2 is 2, which is the right middle index. the left middle index is 1. not 3.


#5

You’re right! Indexs start from 0 so i should be selecting 1 and 2 as the index.

However, that still doesn’t explain why it throws an error if the calculation is within the index range (albeit the wrong one i want).


#6

that problem is here:

answer = l[(n+1)/2]

the length of a list with one item is one. one + one is two. two / two is one. But a list with a single item only has index 0


#7

again you are completely right.

I changed my code to this and finally cracked it.

answer = ((l[(n/2)]) + (l[(n/2)-1])) / 2.0
    return answer
  else:
    answer = l[(n/2)]

Thinking about what you said, using this code answer = l[(n/2)] with only 1 item, it would give the answer 0.5 which would be incorrect as i’d be looking for 0. I’m guessing it automatically changes it into an integer and not a float so defaults to 0? I can fix it by adding subtracting 0.5 from the equation however just figuring out how python does things in the background.


#8

in python2, if the division involves two integers, python will floor (round down) the result to the nearest integer. This is why you will get a problem here:

answer = ((l[(n/2)]) + (l[(n+2)/2])) / 2

because if the list is [4, 5, 5, 4] we get:

9 / 2

which will give 4, while it should give 4.5

so one one hand, this division behavior is useful, on the other hand its annoying


#9

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