15.median question - it works fine on python IDLE, but not on site

Hi,

Here’s the code I’m using for this exercise:

def median(lst):
    srt_lst = sorted(lst)
    cnt = len(srt_lst)
    avg = round(cnt/2)
    result = 0
    e1 = 0
    e2 = 0
    if cnt % 2 == 0:
        e1 = srt_lst[avg]
        e2 = srt_lst[avg - 1]
        result = (e1 + e2)/2
        return result
    else:
        result = srt_lst[avg-1]
        return result

print median([1,1,2])

When I run this on the python shell it runs fine, but on the site shell I get this error:

Oops, try again. Your code did not run to end. Check the console window for errors!

Traceback (most recent call last):
  File "python", line 17, in <module>
  File "python", line 14, in median
TypeError: list indices must be integers, not float

you IDLE runs most likely python3, which is not backward compatible with python2.

i suspect round() behaves different in python2, as you can see:

def median(lst):
    srt_lst = sorted(lst)
    cnt = len(srt_lst)
    avg = round(cnt/2)
    result = 0
    e1 = 0
    e2 = 0
    if cnt % 2 == 0:
        e1 = srt_lst[avg]
        e2 = srt_lst[avg - 1]
        result = (e1 + e2)/2
        return result
    else:
        print avg-1
        result = srt_lst[avg-1]
        return result

print median([1,1,2])

round() gives a float, if you run this in your IDLE it will be different (don’t forget the parentheses for print avg-1

Yeah, I just figured out what happened, maybe my script is over complicated but it finally worked, thank you for the response.

1 Like

well, optimizing your code would be a good challenge, if you are in for a challenge you can try to optimize it :slight_smile:

Not sure if I’m quite up for that yet, though with your help I did manage to get it working, so thanks again! :laughing: