Median 15/15

#1
``````def median(numbers):
length = len(numbers)

if length == 1:
median = numbers[0]
elif length > 1:
numbers.sort()
center = length/2

if length % 2 == 0:
lower = center - 1
#upper = center
median = (numbers[center] + numbers[lower])/2.0
else:
oddcenter = int(center - 0.5)
median = numbers[oddcenter]

return median
``````

This works on every other test scenario but I get " "median([6, 8, 12, 2, 23]) returned 6 instead of 8"
Error doesn’t make sense when I work it out.
After sort:
[2,6,8,12,23]
length = 5
center = 2.5
I want index 2 so I do int(center -0.5).
So how is my math different from what python sees?

#2

5 / 2 -> 2
2 - 0.5 -> 1.5
int(1.5) -> 1

Verify yourself by adding prints in your code (that’s how you’d debug this)

#3
``````x = [2,6,8,12,23]
n = len(x)
m = int(n / 2)
``````

#4

Thanks! forgot/didn’t know division by 2 worked that way.

#5

Only needed to change this line:

oddcenter = int(length/2.0 - 0.5)

thanks for the help!

#6

It’s because both operands are ints, so they keep the type instead of suddenly out of nowhere producing a float

In python3 you would get a float instead (de-emphasis on the particular type, it’s a number)

There’s an operator `//`
In python2 you’d use it to indicate that you indeed mean integer division, and in python3 you use it to avoid floating point division (floats are often something to be avoided because they are not exact)

#7

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