Practice Makes Perfect: Median - Code not calculating correctly



<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 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.


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

<do not remove the three backticks above>


division behavior is different for python2 then python3:

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

if you run on 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

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


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


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