Practice makes perfect 15/15, code problem!


#1

Hello guys, I ran into a weird thing today, the same piece of code returns a value in PyCharm and a different one in the Web application of Code Academy.

this is the code:

def median(l):
    l.sort()
    n = len(l)
    if n % 2 == 1:
        return (l[int((n / 2) + 0.5)])
    else:
        return ((l[int(n / 2)] + l[int(n / 2 - 1)]) / 2.0)
print(median([1, 1, 2]))

Now, in PyCharm this returns “2”.
In the Code Academy Web app it returns “1”.

Obviously, my question is: why ???


#2

this raises an obvious question, what is the difference between your pycharm and codecademy? What differences could there be? What do you think?

see if you can break down this line:

return (l[int((n / 2) + 0.5)])

what is working is differently, given this seems to be the culprit, tear that line of code apart, see what you can come up with

of course i could tell you the answer, but where is the fun in that? :wink:


#3

Thank you very much!
I got it now!

So, in Code Academy it’s Python 2, which means that:

int( (3 / 2) + 0.5) returns 1, because ( 3 / 2 ) is 1 and int(1.5) is 1.

In PyCharm, using Python 3:

int( (3 / 2) + 0.5) returns 2, because (3 / 2) is 1.5 and int(2) is 2.

Gotta pay more attention…

Thank you again, especially for making my brain work on its own.


#4

yes, this better then me just giving you the answer

now, there is something called floor division. Using this, would make your code work for both python versions.


#5

Yeah, I just used the floor division now and it works on both versions!


#6

The most important thing you hopefully learned is not that you solved the problem, but how you solved the problem. What steps it takes to solve a problem.

programming is mostly problem solving and coming up with solutions. Actually implementing the solution is just a small part


#7

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