Median. That should work!


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/median?action=lesson_resume

<In what way does your code behave incorrectly? Include ALL error messages.>
median([6, 8, 12, 2, 23]) returned 6 instead of 8

<What do you expect to happen instead?>
i should return 8. and It does with the python version i use on my pc. I am using python 3
What python version is used at codeacademy?

```python
def median(x):
    x.sort()
    if len(x) % 2 == 0:  # if even
        return (x[int(len(x) / 2)] + x[int((len(x) / 2) - 1)]) / 2.0
    else: # if uneven
        return x[int((len(x)/2)-0.5)]
<do not remove the three backticks above>

#2

codecademy uses python2, the problem is here:

return x[int((len(x)/2)-0.5)]

for a list like [6, 8, 12, 2, 23] the length is 5, but the math is different for the different python version, python3:

# python3
print(5 / 2) # 2.5
print(int(2.5 - 0.5)) # 2
# python2
print(5 / 2) # 2
print(int(2.5 - 0.5)) # 1

I don’t see why you would use -0.5, int() will floor (round down) so there is no need to subtract 0.5, making it work in both python versions


#3

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