Median


#1



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


Oops, try again. median([6, 8, 12, 2, 23]) returned 12 instead of 8


def median(unsorted):
    nbs = sorted( unsorted )
    if len(nbs)%2 != 0 and len(nbs) != 1:
        return nbs[(len(nbs)+1)/2]
    elif len(nbs) == 1:
        return nbs[0]
    else:
        return (nbs[len(nbs)/2] + nbs[(len(nbs)/2)-1])/2.0


#2

here:

return nbs[(len(nbs)+1)/2]

why +1?


#3

because to find the median we must add 1 and divide by 2


#4

why must we add one?


#5

cuz we have an odd number of items (5 in the given case) and to divide them and find their median that seperate the numbers to two equal sets we must add one so we have an even number of items thus divisible by 2


#6

but for a list of 5, the indexes are: 0, 1, 2, 3 and 4

so 5 / 2 = 2, which is the middle index, so again i will ask, why add 1?


#7

oh got it, thank you


#8