Reputation: 43
I am writing a filter function such that when I insert my wave number, which is a list of numbers, the filter_wave_num function will be executed n times to change the wave number.
However, it doesnt seem to work, it repeats the output only once, when I want it to do it n times. Will appreciate your help in this.
def filter_wave_num(wave):
new_wave = []
for i in range(len(wave)):
if i == 0:
new_wave.append(int(wave[i]*0.6 + wave[i+1]*0.2))
elif i == len(wave)-1:
new_wave.append(int(wave[i-1]*0.2 + wave[i]*0.6))
else:
new_wave.append(int(wave[i-1]*0.2 + wave[i]*0.6 + wave[i+1]*0.2))
return new_wave
def filter_wave(wave,n):
for i in range(n):
filter_wave_num(wave)
return filter_wave_num(wave)
wave = [600, 3200, 7600, 13400, 18400, 22600, 24400]
# each element inside the list has to be changed n times
Upvotes: 0
Views: 250
Reputation: 327
Store all the iteration results in a list and then return it:
def filter_wave(wave,n):
result = []
for i in range(n):
wave = filter_wave_num(wave)
result.append(wave)
return result
Upvotes: 0
Reputation: 81
You do call your function n times, but you are calling it with the same input so you get the same output after all iterations. Here's what you need to do: Notice that I changed the name of 'i' to '_', this is a convention indicates we don't need to use the value of this variable
def filter_wave(wave,n):
result = wave
for _ in range(n):
result = filter_wave_num(result)
return result
Upvotes: 1
Reputation: 7361
The filter_wave_num
function works.
If you need to use it recursively n times (each time on the result obtained the previous time) modify your second function like this:
def filter_wave(wave, n):
for _ in range(n):
wave = filter_wave_num(wave)
return wave
The function you have written creates each time a new list, but you don't return the result each iteration and it's lost.
Upvotes: 2