Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading