-1

could someone explain in detail on this ((sum(x[i-n:i+n+1]))..where does i-n:i+n+1 start and end?? i just don't want to copy the code`

The function should create a return a new list r where

def smooth_a(x, n):
    x = [x[0]]*n+x+[x[-1]]*n #creates a copy of x  
    res = [] #empty list     
    for i in range(n, len(x)-n):
        res.append(sum(x[i-n:i+n+1])/(2*n+1)) 
    return res 

x = [1, 2, 6, 4, 5, 0, 1, 2] #def of x
print('smooth_a(x, 1): ', smooth_a(x, 1)) #prints new list with n=1 
Anentropic
  • 32,188
  • 12
  • 99
  • 147

1 Answers1

0

Let's say x = [1, 2, 6, 4, 5, 0, 1, 2] and n = 1

Then, if you take i = 3 for example:

sum(x[i-n:i+n+1]) = sum(x[2:5])
                  = sum([6, 4, 5]) <- slices x from 2 to 4, both inclusive
                  = 15

For your specific problem, be careful with the lower slice index, if it's negative, the slicing will return an empty list, so I would write it as sum(x[max(i-n, 0):i+n+1]).