Median


#1



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


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


The sorted list is [4,4,5,5] and I am retrieving values from the sorted list. What is wrong with my code?


def median(first_list):
    second_list=sorted(first_list)
    length=len(first_list)
    if length%2==0:
        return (second_list[(length/2)-1]+second_list[(length/2)])/2
    else:
        return second_list[((length+1)/2)-1]


#2

this is the problem:

print 9 / 2 # 4

this should output 4.5, but python floors (round down) the number if the division uses two integers. Knowing this we can solve the problem by using float


#3

Thanks @stetim94. Solved it using the below code.


#4

This really tripped me up, because I use IDLE as my practice Python shell outside of Codecademy, and this code worked:

def median(loi):
    loi = sorted(loi)
    if len(loi) % 2 == 0:
        a = int(len(loi) / 2)
        b = int(len(loi) / 2 - 1)
        return (loi[a] + loi[b]) / 2
    else:
        c = int(len(loi) / 2 - 0.5)
        return loi[c]

Does anyone know why it would work in IDLE, but not in Codecademy? Is it to do with the version of Python, or perhaps there's a setting that doesn't floor integer division that I don't know about?

Thanks!


#5

a change was made in division behavior when python3 was released, dividing an integer by an integer no longer gets floored (round down) in python3


#6

Ah, okay good to know! Same reason I can print without brackets in Codecademy, but need brackets in IDLE. (although I've been training myself to bracket everything after print regardless)

Thank you!!


#7

in python2, print was a statement, in python3 its a function

be careful wit the parentheses/brackets, for example doing this in python2:

x="world"
print("hello", x)

might cause unintended side effects (given the parentheses cause it to become a tuple (immutable list)


#8

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