Median exercise


#1


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

If i run the code in IDLE, the result is corect, but in the codecademy site, it says that:
Oops, try again. median([4, 5, 5, 4]) returned 4.0 instead of 4.5
Am i doing something wrong?
Thank you in advance


def median(lista):
    calculation = 0
    median = 0
    lista.sort()
    #print (lista)
    #print (len(lista))
    if len(lista) <= 1:
        calculation1 = int(len(lista) / 2)
        avg1 = (calculation1) - 1
        
        calculation2 = calculation1

        AvgFinal = (lista[avg1] + lista[calculation2]) / 2

        return AvgFinal
    elif len(lista) % 2 != 0:
        calculation = int(len(lista) / 2) + 1
        median = lista[calculation]
        return median
    else:
        calculation1 = int(len(lista) / 2)
        avg1 = (calculation1) - 1
        
        calculation2 = calculation1

        AvgFinal = float((lista[avg1] + lista[calculation2]) / 2)

        return AvgFinal
        #print(calculation1)
        print(lista[avg1])
        print(lista[calculation2])


#2

your IDLE very likely runs python3, a change was made to division behavior:

# python3
print(9 / 2) # 4.5
#python2
print 9 / 2 # 4

in python2 (which codecademy runs) dividing an integer by an integer results an integer the result is floored/round down if needs be

yes, you use float() but after the division, so the rounding down has already been done. The division itself should involve a float


#3

Thank you for replying so fast. I made it work.
I had one more mistake on the elif branch.


#4

good, nicely done :slight_smile: Seems you not only fixed the problem, but also understand it, also pretty important :wink:


#5

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