Median again


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096#


Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5


I checked my code by IDLE and it works there (I see 4.5 as a result of test).


def median(lst):
    '''(list) -> float

    >>>median([1,1,2]) 
    1
    >>>median([1,3,6,7,12])
    6
    >>>median([7,3,1,4])
    3.5
    >>>median([4, 5, 5, 4])
    4.5
    
    '''
    lst_sort = sorted(lst)
    
    if len(lst_sort) % 2 == 0:
        m = (lst_sort[int(len(lst_sort) / 2 - 1)] + lst_sort[int(len(lst_sort) / 2)]) / 2 
    else:
        m = lst_sort[int((len(lst_sort) - 1) / 2)]
    return m


#2

Sorry, do not react, I found my mistake. 2.0 instead 2. I should read hint more carefully.


#3

good job. Your IDLE very likely runs python3, which made a fundamental change to how division is done:

#python3
9 / 2 # 4.5
#python2
9 / 2 # 4

#4

Ohho) I am just a beginner and do not know all details - but yes, my IDLE runs python 3. Thank you, now I know that the difference between 2 and 3 could be important even for beginners.


#5

another fundamental difference is that in python3 print requires parentheses

You might want to look up online what the differences are


#6

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