Median help (Solved)


#1

Getting median([4, 5, 5, 4]) returned 4 instead of 4.5 error


def median(series):
    series=sorted(series)
    length=len(series)
    if length % 2 == 0:
        first=series[(length / 2)]
        second=series[(length / 2)-1]
        average=(first + second)/2
        return average
    
    else:
        if length==1:
            return series[length-1]
        else:
            first=float((length+1))/2
            return series[first-1]


#2

this is the division you make:

9 / 2

the problem is that dividing two integers, will give an integers as a result, so you need to do something with a float


#3

when i do this:

average=float((first + second))/2

i get a different error:
median([6, 8, 12, 2, 23]) resulted in an error: list indices must be integers, not float


#4

but [6, 8, 12, 2, 23] is a list with a odd number of items? Which means your code has another problem, here:

first=float((length+1))/2

first is a float, list indexes can only be integers


#5

Thank you!
that solved it


#6