Home > Net >  Which part of my function is causing TypeError: list indices must be integers or slices, not float?
Which part of my function is causing TypeError: list indices must be integers or slices, not float?

Time:10-30

I am creating a median_filter function for an assignment. Here is my code:

def median_filter(y, W):
    """ (list, int) -> list
    
    Returns a list whose ith item is
    the median value of y[start:stop 1] where
    start is the larger of 0 and i - W and
    stop is the smaller of i   W and n-1.
    
    >>> median_filter([-1.0, 6.0, 7.0, -2.0, 0.0, 8.0, 13.0], 1)
    [2.5, 6.0, 6.0, 0.0, 0.0, 8.0, 10.5]
    """

        
    for i, element in enumerate(y):
        
        ynew = []
        
        if i-W >= 0 and i W < len(y):  
            ynew.append([my_median([y[i-W],y[int(i)], y[i W]]) for i in y])
            
        
        if i-W < 0 and i W < len(y): 
            ynew.append([my_median([y[0], y[1]]) for i in y])
            
            
        if i-W >= 0 and i W >= len(y):
            ynew.append([my_median([y[len(y)-2], y[len(y)-1]]) for i in y])
            
        i =1
        
    return ynew

It gives this error:

Traceback (most recent call last):
      File "C:\Users\*****\Desktop\****\", line 339, in <listcomp>
        ynew.append([my_median([y[i-W],y[int(i)], y[i W]]) for i in y])
    TypeError: list indices must be integers or slices, not float

Why am I getting this error? How can i resolve it?

edited to add instructions to function: enter image description here

CodePudding user response:

Here is the code they were trying to get you to write.

def median_filter(y, W):
    """ (list, int) -> list
    
    Returns a list whose ith item is
    the median value of y[start:stop 1] where
    start is the larger of 0 and i - W and
    stop is the smaller of i   W and n-1.
    
    >>> median_filter([-1.0, 6.0, 7.0, -2.0, 0.0, 8.0, 13.0], 1)
    [2.5, 6.0, 6.0, 0.0, 0.0, 8.0, 10.5]
    """

    ynew = []

    for i in range(len(y)):
                
        if i-W >= 0 and i W < len(y):  
            val = my_median( y[i-W:i W 1] )
                    
        elif i-W < 0 and i W < len(y): 
            val = my_median( y[0:y[i W 1] )
                        
        elif i-W >= 0 and i W >= len(y):
            val = my_median( y[i-W:] )

        ynew.append( val )
            
    return ynew

Even easier is:

    ynew = []
    for i in range(len(y)):
        ynew.append( my_median( y[max(0,i-W):min(i W 1,len(y))] ) )
    return ynew
  • Related