# Practise makes perfect - median

#1

Hi guys, I have some problem with this exercise and the following is my code:

``````def median(lista):
lista.sort()
lun = len(lista)
if lun % 2 == 0 and lun != 0:
a = lista[(lun / 2)]
b = lista[((lun / 2) + 1)]
c = float
c = round (a + b) / 2
return c
elif lun == 1:
return lista[0]
else:
return lista[(lun / 2) + 1]``````

And this is the error I get:

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

I think It is a matter of approximation but I don't know precisely how to fix it...can anyone please help me?
Thank you

#2

if the length of the list is 4, the indexes are: 0,1,2,3

so the indexes we need are 1 and 2, in other words: length / 2 and length / 2 -1

minus one, not plus one

#3

You're right, typical of the moments when you are tired.

The problem is that there is still a problem of approximation:

``````def median(lista):
lista.sort()
lun = len(lista)
if lun % 2 == 0 and lun != 0:
a = lista[(lun / 2)]
b = lista[((lun / 2) - 1)]
c = float
c = round((a + b) / 2, 2)
return c
elif lun == 1:
return lista[0]
else:
return lista[(lun / 2) - 1]``````

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

#4

i helped with the error you where stuck at for a while? did you take a minute to see why this new error message might arise?

#5

Yes, but I didn't understand, otherwise I would make everything by myself.

#6

well, `round()` will round a number, you don't want this, since you want to output 4.5

here is what you do, remove this line:

``c = float``

now, add a and b together, and divide by a float (`2.0`) this way, you get a float as result, rather then an integer. keep order of operation in mind

#7

The problem was that I am new with this language, now I have reminded that i need a float to obtain a float as a result.
Thank you!

#8

problem resolved?

#9

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