new_to_sql_python
new_to_sql_python

Reputation: 11

Filtering a Wave

I am trying to write a function filter_wave(wave,1) and this will produce a new wave which is a smoothed version of the input wave. Following the rules below:

In the new wave, for every position i, it is the weighted sum of three positions of the original wave. Specifically, the new wave value in position i will be equal to

new_wave[i] = wave[i-1] * 0.2 + wave[i]*0.6 + wave[i+1]*0.2

some of the conditions:

I have written the following code but not sure what are the issues exactly since the program keeps returning 0

def filter_wave(wave,times):
    new_wave = []
    for i in range(len(wave)):
        if wave[i-1] < wave[0]:
            return 0
        if wave[i+1] > len(wave):
            return 0
    new_wave = wave[i-1] * 0.2 + wave[i]*0.6 + wave[i+1]*0.2
    new_wave.insert(i,int(new_wave))
    return new_wave

Upvotes: 0

Views: 467

Answers (2)

New Python learner
New Python learner

Reputation: 41

I wonder if this will work.

def filter_wave(wave, times):
    L = len(wave)
    new_wave = []

    for i in range(times):            
        for j in range(L):
            if j == 0:                        #wave[-1] = 0                          
                new_wave[j] = int(wave[j] * 0.6 + wave[j + 1] * 0.2)
            elif j == L - 1:                  #wave[L] = 0          
                new_wave[j] = int(wave[j - 1] * 0.2 + wave[j] * 0.6)
            else:
                new_wave[j] = int(wave[j - 1] * 0.2 + wave[j] * 0.6 + wave[j + 1] * 0.2)
            
    return new_wave

Upvotes: 0

Tim Roberts
Tim Roberts

Reputation: 54708

There are better ways to do this, but this is parallel to your choices.

def filter_wave(wave,times):
    new_wave = []
    for i in range(len(wave)):
        if i == 0:
            prev = 0
        else:
            prev = wave[i-1]
        if i+1 >= len(wave):
            nxt = 0
        else:
            nxt = wave[i+1]
        new_wave.append( prev * 0.2 + wave[i] * 0.6 + nxt * 0.2 )
    return new_wave

Alternative, which handles the endpoints outside the loop, thereby making the loop simpler:

def filter_wave(wave,times):
    new_wave = []
    new_wave.append( wave[0] * 0.6 + wave[1] * 0.2 )
    for i in range(1, len(wave)-1):
        new_wave.append( wave[i-1] * 0.2 + wave[i] * 0.6 + wave[i+1] * 0.2 )
    new_wave.append( wave[-2] * 0.2 + wave[-1] * 0.6 )
    return new_wave

Upvotes: 2

Related Questions