Median. Code works on computer, but not in excercise


#1

Hey all. So my code needs to find the median number in a list of numbers. I made a code, and tested it in IDLE on my computer, and it works, but in the specific exercise, Codecademy says"Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5". But when I tested it, that same list gave me 4.5 on my computer.

def median(number_list):
number_list = sorted(number_list)
print('sorts the number list' + str(number_list))
if len(number_list) == 1:
    print('entering if statement 1')
    median_value = number_list[0]
    print('median defined 1')
else:
    print('entering else statement 1')
    if (len(number_list) % 2 != 0):
        print('entering if statement 2')
        median_value = number_list[round(len(number_list) / 2) + 1]
        print('median defined 2')
    else:
        print('entering else statement 2')
        median_value = (((number_list[int(len(number_list) / 2)]) + \
        (number_list[int(len(number_list) / 2) - 1])) / 2)
        print('median defined 3')
print('median value = ' + str(median_value))
return median_value

I added print statements to see how the code progressed when calling different lists.


#2

try this

def median(number_list):
    number_list = sorted(number_list)
    print('sorts the number list' + str(number_list))
    if len(number_list) == 1:
        print('entering if statement 1')
        median_value = number_list[0]
        print('median defined 1')
    else:
        print('entering else statement 1')
        if (len(number_list) % 2 != 0):
            print('entering if statement 2')
            median_value = number_list[len(number_list) / 2]
            print('median defined 2')
        else:
            print('entering else statement 2')
            median_value = (((number_list[len(number_list) / 2]) + \
            (number_list[len(number_list) / 2 - 1])) / 2.0)
            print('median defined 3')
    print('median value = ' + str(median_value))
    return median_value 
    

print median([4,5,7,9,3,6]) #5.5