Error in Codecademy but not in Python 3.4


#1

Hi There,

I'm working through Practice Makes Perfect problem "Median" and I keep recieving an error message when the program attempts to run list [4,5,5,4] through my code. The console states that I am getting an answer of 4 instead of 4.5. However when I run the same program in my installation of Python 3.4 return the correct median of 4.5.

Possible bug? Code pasted below for reference.

import math
def median(somelist):
somelist = sorted(somelist)
if len(somelist)%2 != 0:
return somelist[int(math.floor(len(somelist)/2))]

else:
    return (somelist[int(len(somelist)/2)] + somelist[int(len(somelist)/2)-1])/2

#2

Hi @tinylion,

Codecademy uses a few different minors of the 2.7.x branch and what you are describing is not a bug but the standard behavior for the division operator in Python 2.x, C/C++ and Java.

As described in this PEP238 Python Doc, Python 3.x adopts a different behavior for the divison operator.

Here's the gist of it:

In Python 2.x, the division operator will perform floor division when give only integer operands. If one operand is a float, it will return a float.

So In Python 2.x:

print (5 + 4) / 2          # will yield 4
print (5 + 4) // 2         # will yield 4 when using floor division operator //

print (5 + 4) / 2.0        # will yield 4.5
print (5 + 4) // 2.0       # will yield 4 when using floor division operator //
print (5 + 4.0) / 2        # will yield 4.5
print (5.0 + 4) / 2        # will yield 4.5
print (5.0 + 4.0) / 2.0    # will yield 4.5

In Python 3, the behavior of the / operator was changed and therefore:

print((5 + 4) / 2)         # will yield 4.5
print((5 + 4) // 2)        # will yield 4 when using floor division operator //

So you would just need to adjust your code like so to have it work both in 2.x and 3.x:

import math

def median(somelist):
    somelist = sorted(somelist)
    if len(somelist)%2 != 0:
        return somelist[int(math.floor(len(somelist)/2))]
    else:
        return (somelist[int(len(somelist)/2)] + somelist[int(len(somelist)/2)-1])/2.0

or if you wish to have Python 2.x divide like Python 3.x:

from __future__ import division    # this will make / in Python 2.x
                                   # acts like / in Python 3.x

import math

def median(somelist):
    somelist = sorted(somelist)
    if len(somelist)%2 != 0:
        return somelist[int(math.floor(len(somelist)/2))]
    else:
        return (somelist[int(len(somelist)/2)] + somelist[int(len(somelist)/2)-1])/2

Hope this helped :smile: