15/15 Median


#1

I don't understand what I'm doing wrong. It keeps saying that I'm returning the wrong value on an even list. The list it gives is [0,1,1,6,8,34] and for some reason I'm getting a return of 4.5 instead of 3.5. I think it has to do with the int() change from a float but I'm not sure. Thank you.

def median(num):
    num = sorted(num)
    total = 0
    if len(num) % 2 == 0:
        total = len(num) / 2.0
        total = (num[int(total+1)] + num[int(total-1)]) / 2.0
        return total
    else:
        total = int(len(num) / 2.0)
        total = num[total]
        return total

#2

Nevermind, I'm an idiot. I just realized that lists are indexed starting at 0. I just had to remove the +1 after int(total+1)


#3

Also, you shouldn't be doing floating point math when your end result is supposed to be an integer (an index)

Makes no difference in this case (floats can exactly represent 0.5 (2**-1)), but you really should not do that.


#4

Thanks for the tip. May I ask how you would fix it for future reference? The tip on the lesson said that doing just / 2 could possibly return a wrong number when working on an even list. I just assumed it wanted me to use 2.0 so I'd be covered if a float was returned.


#5

Indexes should never end up ending with .5, you should only ever be doing integer operations on them.

It's good to use // for integer division to show that's what you mean, and that also makes it behave consistently between Python2 and Python3.

What I would do.. is to use Python3 because it's quite far ahead by now, the only reason that remains is to not want things to change (like tools that do various system tasks on linux distros, for the record my system runs fine if I uninstall python2, but Debian and the such would rather nothing ever changed)


#6

Thank you for the information. I feel a bit stupid because I'm not even sure of the differences in python2 and python3. This is all brand new to me since I just took my first look at code about 2 weeks ago.


#7

The differences aren't big. They aren't backwards compatible though.

Python3 is better. The backwards break also caused a whole lot of trouble.

The clock is starting to run out for Python2, it's in maintenance mode until 2020ish unless that gets extended further


#8

Good to know, if I ever do anything outside of the website I'll certainly know to use Python3 so I don't end up wasting my time.


#9

The problem isn't in learning both versions, they have far more in common than they differ, just google when differences are encountered.

The problem is in rewriting old code lying around that is relying on old cruft.

Code can be written to run with both and the way one should be writing Python2 is still using several of the new things.