Exercise 15: Median - 15. Practice Makes Perfect [python2 and 3 confusion]


#1

I’ve tried my code on python3 and it seems to be working perfectly fine, so after look through a bunch of the same thread regarding this topic, I’ve found one that manage to closely resemble my problem.

Here is my code:

from math import ceil

def median(x):
  lst = x
  thing = 0
  lst.sort() #[2,6,8,12,23]
  if len(lst)%2>0: #which is true
    thing = (len(lst)/2) - 1 #len(lst) = 5, and 5/2 = 2 (according to python2)
    thing = ceil(thing) #ceil(2) = 2
    print(thing) #output is -1.0, 1.0?!?!?, wot?!!
    return (lst[int(thing)])
  else:
    val1 = int(len(lst)/2) - 1
    val2 = int(len(lst)/2)
    result = (x[val1] + x[val2])/2.0
    return result

According to this thread: [SOLVED]: median([4, 5, 5, 4]) returned 4.0 instead of 4.5 but code works in console - python2 has a different nature for division. I’ve followed up on it and fixed the second body of the code beneath the “else” statement - I changed “2” to “2.0”, which worked!

It managed to pass through a few arguments, but got stuck on argument “[6, 8, 12, 2, 23]” as seen below:

I’ve annotated the code as well.


#2

here:

thing = (len(lst)/2) - 1 #len(lst) = 5, and 5/2 = 2 (according to python2)

5 / 2 is 2, 2 is the middle index so why subtract one? then you are at index 1


#3

oh, you are right!, it works now! o-0. The reason that I’ve subtracted one from my code is how the “Len” function behaves. I did a test before and found out that unlike list, the “len” functions starts counting from 1, and listing starts counting from 0, so I decided to subtract it based on this theory - apparently it works on python3, but now that I look at it - it’s out of pure misleading coincidence o-0.

Again, thanks for your help :smiley: - you’re a very helpful person :+1:


#4

that is because in python3, 5 / 2 result in 2.5. 2.5 - 1 is 1.5, ceil(1.5) is 2

ideally, i would use to avoid ceil(). we have floor division:

# python3
print(5//2) # 2
# python2
print 5 // 2 # 2

which i think is a much better way of making your code work in both versions of python


#5

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