Stuck in median


Argh, what would be wrong with this one?

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

So what I try to do is first to to do if/else loop to determine if there is even or odd number of numbers in list.
Next, in even calculate the indexes and then average for two middle numbers.
In the odd list else-loop the len(list) results always in x.5 kind of result so I should take out 0.5 to get the index of the middle number?

def median(lst):
    nlst = sorted(lst)
    if len(nlst) % 2 == 0:
        ind = len(nlst)/2
        ind2 = ind-1
        mediaani = (nlst[ind] + nlst[ind2]) /2
        return mediaani
        ind = len(nlst)/2-(1/2)
        mediaani = nlst[ind]
        return mediaani


lets do an example:

11 / 2

this will result in 5. Python will floor (round down) numbers when the division involves integers (non decimal numbers) only

so here:

ind = len(nlst)/2-(1/2)

you don't need to subtract -0.5, given python already floored the number

on the other hand, here:

mediaani = (nlst[ind] + nlst[ind2]) /2

it causes a problem, because the result will be an integer. you will need to use a float (decimal number or float()) to get a float result


Thank you so much! Now it is working :sweat_smile: