I am learning Python and one of the exercises from the course I am taking is to create a function that calculates the moving average of all elements in a vector, given a window of elements. The only exceptional cases is near the edges where there are not enough neighbours then the edge value must be repeated. I wrote the following function, which is not working:
%reset -f
def moving_window_average(x, n_neighbors):
mavg=[]
i=0
while i<=len(x):
sumv=[x[i]]
j = n_neighbors
while j>0:
if (i-j)<0:
sumv.append(x[i])
sumv.append(x[i+j])
j-=1
elif (i+j)>len(x):
sumv.append(x[i])
sumv.append(x[i-j])
j-=1
else:
sumv.append(x[i-j])
sumv.append(x[i+j])
j-=1
mavg_i=sum(sumv)/len(sumv)
mavg.append(mavg_i)
i+=1
return mavg
x = [0,10,5,3,1,5]
print(moving_window_average(x, 1))
But when I run line by line it works (like below) it works fine for me
mavg=[]
i=0
#while i<=len(x):
i<=len(x)
sumv=[x[i]]
j=1
#while j>0
j>0
#
(i-j)<0
sumv.append(x[i])
sumv.append(x[i+j])
j-=1
#
(i+j)>len(x)
sumv.append(x[i])
sumv.append(x[i-j])
j-=1
# else
sumv.append(x[i-j])
sumv.append(x[i+j])
j-=1
mavg_i=sum(sumv)/len(sumv)
mavg.append(mavg_i)
i+=1
Can someone please help me? I reckon the solution must be rather simple, but I cannot understand what is wrong in my function. Thank you.