# Bug in "Median" lesson?

#1

I get an error message saying that I get an output of 4 instead of 4.5 when the input list is [4,5,5,4]. However, my code works on repl.it as well as idle. Is this something to do with code academy still using python 2.x?

``````def median(stuff):
stuff.sort()
if len(stuff) % 2 == 0:
return (stuff[ int(len(stuff) / 2) - 1] + stuff[ int((len(stuff) / 2))]) / 2
else:
return stuff[ int((len(stuff) - 1) / 2)]``````

#2

It is because we are using 2.7.x, yes. Unlike 3.x.x, floats are implied only when one of the operands is a float. 1/2 is 0, not 0.5. 1.0/2 will be 0.5.

For the purpose of this lesson, use,

``float(numerator expression) / len(object)``

`len()` always returns an integer, so no explicit declaration required in either version.

If repetition is a concern, then caching of repeated expressions helps reduce it.

``````    sample_space.sort()
m = len(sample_space)
n = m / 2              # in 3.x.x it would be, `n = int(m / 2)`
if m % 2:
return sample_space[n]
else:
return float(sample_space[n-1] + sample_space[n]) / 2``````

Or if you like refactoring... (s_s = sample_space, for brevity)

``return s_s[n] if m % 2 else float(s_s[n-1] + s_s[n]) / 2``

#3

2 posts were split to a new topic: Not sure I follow

#4

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