Practice Makes Perfect - Median!


#1



Practice Makes Perfect - Median !


It works in spyder but not on the site - The error :slight_smile:

Oops, try again. median([1]) resulted in an error: list indices must be integers, not float

I thought I got round this by rounding the float values ?

TY/


def median(imp):
    
    imp.sort()
    midindex2=[]
    length = len(imp)
    
    if length%2 != 0:
        midindex = round((len(imp)-1)/2)
        round(midindex)
        median = imp[midindex]
        return median
    else:
        i = (len(imp)/2)
        i = round(i)-1
        midindex2.append(i)
        t=i
        t = round(t)
        midindex2.append(t)
        return ((imp[midindex2[0]]+imp[midindex2[1]])/2)


#2

from the docs:

round(number[, ndigits])
Return the floating point value number rounded to ndigits digits after the decimal point. If ndigits is omitted, it defaults to zero


#3

As in - round(midindex,[2]) ?


#4

no, round(midindex, 2). But why would you want 2 decimal numbers? The important part of the answer is here:

round clearly gives a float, not a integer, so you can't use round to solve this problem


#5

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