I have an assignment: Create a function smooth(a, n)
which given a list (a) and an integer n>0
will create a new list containing the average value of the current element+(the n elements to its left and right). If the current element is close to either end of the given list, it might not have sufficient element to one of its sides. Should this be the case, the program is to count the first/last (depending on which side is lacking elements) as the next element, and calculate the average based on n using the simple formula 2*n+1
Wall of text, but here's the bulk of it:
For example;
a = [1, 2, 6, 4, 5, 0, 1, 2]
n = 2
print(smooth_a(a, n))
should give the output [2.2, 2.8, 3.6, 3.4, 3.2, 2.4, 2.0, 1.4]
since a[0] = 1
the average is calculated as such: (1+1+1+2+6)/5 = 2.2
(as shown above.
Alright, now to the actual problem:
The program works, but for some reason, the function saves previous modifications to the temporary list temp_a
.
Code looks like this:
def smooth_a(a, n):
r = []
temp_a = a
for i in range(n): #Extend the list with n elements on either side
temp_a.insert(0, a[0])
temp_a.insert(-1, a[-1])
for t in range(n, len(a)-n): #Iterate as many times as a has elements
sum = 0
for p in range(t-n, t+n+1): #Iterate over 2n+1 elements starting n to the left
sum += temp_a[p] #Add value of current element to sum
r.append(sum / (2*n + 1)) #Calculate average and add to list r
return r #Return list containing average values
x = [1, 2, 6, 4, 5, 0, 1, 2]
print('smooth_a(x, 2): ', smooth_a(x, 2))
print('smooth_a(x, 2): ', smooth_a(x, 2))
which gives the output
smooth_a(x, 2): [2.2, 2.8, 3.6, 3.4, 3.2, 2.4, 2.0, 1.4]
smooth_a(x, 2): [1.0, 1.2, 2.2, 2.8, 3.6, 3.4, 3.2, 2.4, 2.0, 1.4, 1.8, 2.0]
When troubleshooting I can see that the first for
-loop does what it's supposed to, but when calling the function again the added elements are still there, even tho temp_a
is being reset to a
at the beginning of the function.
Running VS Code btw (not sure if bug, prob not)
TL:DR Calling functions twice in a row or more seems to "save" certain features to in-function variables. Why?