Practice Makes Perfect: Median - Code not calculating correctly

#1

<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>
I get the error returned 4 instead of 4.5 with list [4,5,5,4]. Code works on other text editors just fine and returns 4.5 as it should. Just not here on codeacdemyâ€™s console.

<What do you expect to happen instead?>
Due to the issues that I have been having with codeacademy after the update recently, I have been typing out my code on a text editor and pasting back into the codeacademy console. My code works perfect in my text editor and even in repl.it online console and returns 4.5 as it should. Both of the editors are on python 3.6. I cant see 2.7 causing any issues here though. Would really like someone to point it out for learning sake.

```python

def median(data):
sort_list = sorted(data)
print(sort_list)
if len(sort_list) % 2 == 0:
mid = int(len(sort_list) / 2)
calc = (sort_list[mid] + sort_list[mid - 1]) / 2
print(calc)
return(calc)
else:
mid = int(len(sort_list) / 2 - .5)
calc = sort_list[mid]
return calc

``<do not remove the three backticks above>``

#2

division behavior is different for python2 then python3:

``````# python3
print(9/2) # 4.5
# python2
print 9 / 2 # 4
``````

if you run on repl.it in python2, you will also see 4

anyway, in python2, when division involves two integers, python will floor (round down) to the nearest integer

to overcome this problem, the division should involve a float

Python: Practice makes Perfect: Lesson 15: Median
#3

Thank you, had a feeling it was a 2vs3 issue

#4

your feeling was right, where you able to solve the problem in python2 by including a float in the division operator?

#5

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