Writing a filtered median function in python

I have an input in list: signal = [0,5,1,1,0,1]

y1 = 0 (signal[0])
y2 = median(0, 5, 1) = 1
y3 = median(5, 1, 1) = 1
y4 = median(1, 1, 0) = 1
y5 = median(1, 0, 1) = 1
y6 = 1 (signal[-1])

The expected output is [0, 1, 1, 1, 1, 1]

My code is:

import statistics
def find_median(number1, number2, number3):
    number1 = float(number1)
    number2 = float(number2)
    number3 = float(number3)
    List = [number1, number2, number3]
    k = statistics.median(List)
    return k

signal = [0,5,1,1,0,1]
med_filter = [signal[0]]
for i in range(signal[0], signal[-3]):
  x = find_median(signal[i], signal[i+1], signal[i+2])
  med_filter.append(x)
med_filter.append(signal[-1])
print(med_filter)

I dont know why my code does not generate the same result as the expected output…

>Solution :

You are iterating over a range constructed from the values in the list – rather than the indexes. Change your for-loop to this:

signal = [0, 5, 1, 1, 0, 1]
med_filter = [signal[0]]
for i in range(0, len(signal) - 2):  # indexes that you need to iterate over
    print(signal[i], signal[i + 1], signal[i + 2])  # check which values are being used
    x = find_median(signal[i], signal[i + 1], signal[i + 2])
    med_filter.append(x)
med_filter.append(signal[-1])
print(med_filter)

Result:

0 5 1
5 1 1
1 1 0
1 0 1
[0, 1.0, 1.0, 1.0, 1.0, 1]

Leave a Reply