Median calculation in the course


#1

Blockquote
def median(lst):
sorted_list = sorted(lst)
if len(sorted_list) % 2 != 0:
#odd number of elements
index = len(sorted_list)//2
return sorted_list[index]
elif len(sorted_list) % 2 == 0:
#even no. of elements
index_1 = len(sorted_list)/2 - 1
index_2 = len(sorted_list)/2
mean = (sorted_list[index_1] + sorted_list[index_2])/2.0
return mean

print median([2, 4, 5, 9])

This code was given as a solution for the ‘Median’ and works fine on the website.
When I use it in my Python IDLE 3.6.2 it gives an error message.
It seems, that this version returns a float even when dividing with an integer.
The index_1 and index_2 variables have to be converted to an integer.
index_1 = int(len(sorted_list)/2 - 1)

Is there an option in the Python IDLE to be set to guarantee a division by an integer returns an integer?


#2

just use the int() around the division you want to become a integer instead of a float:
ex:

print(2/3)
0.66666666
print(int(2/3))
0

#3

Python 3 differs slightly from Python 2. The more obvious differences are with print (which is now a function) and the way Python treats rationals.

5/3  =>  1                    # Python 2

5/3  =>  1.6666666666666667   # Python 3

In Python 2 we need to explicitly declare a float when computing quotients. Some folks are keen on the idea of using the decimal point to invoke a float…

(a + b) / 2.

while others, such as myself are more bent on using the float() function…

float(a + b) / 2

Either way is fine, of course, and in Python 3 not a requirement. However, now the opposite is true. If we want an integer result in Python 3 we have either to declare it explicity.

int(a / b)

or to use floor division,

a // b

Median
def median(sample):
    s = sorted(sample)
    n = len(s)
    m = n // 2
    return s[m] if n % 2 else float(s[m - 1] + s[m]) / 2

#4

No no no

Stick with integer operations, don’t convert back to int after an approximate operation


#5

Is that a practice thing, or is there a proneness to error?


#6

I understand, that you could use both ways: floor division // instead of regular division / or conversion to int().
This makes the program usable in both versions.


#7

floats are approximations, considering whether an operation is exact is just saying float isn’t the data type you want


#8
return s[m] if n % 2 else float(s[m - 1] + s[m]) / 2

It’s pretty clear which return value is the approximation. I never thought of it in those terms before, and have probably been missing the boat as a result. Thanks for bringing it to my attention.

What’s weird is that I comprehend Newtonian approximations. Bringing it into my paradigm didn’t seem to happen.


#9

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