4. The following code attempts to implement a moving average filter but raises an error. What is the error and how to fix it?
data = [2, 4, 6, 8]
window = 3
filtered = []
for i in range(len(data)):
avg = (data[i] + data[i+1] + data[i+2]) / window
filtered.append(avg)
print(filtered)
medium
A. IndexError because indexing goes beyond list end; fix by using range(len(data)-window+1)
B. ZeroDivisionError because window is zero; fix by setting window to 1
C. TypeError because sum cannot add list slices; fix by converting slice to list
D. No error; code runs correctly
Solution
Step 1: Identify the error cause
Loop runs till len(data), but indexing data[i+2] exceeds list length at end.
Step 2: Fix the loop range
Change loop to range(len(data)-window+1) to avoid out-of-range indexing.
Final Answer:
IndexError because indexing goes beyond list end; fix by using range(len(data)-window+1) -> Option A
Quick Check:
Loop range must prevent out-of-bound indexing [OK]
Hint: Loop till len(data)-window+1 for safe indexing [OK]
Common Mistakes:
Ignoring index bounds causing IndexError
Changing window size incorrectly
Assuming no error occurs
5. You want to build a real-time DSP pipeline that filters noise from a sensor signal using a moving average filter of window size 4, but the sensor sometimes sends fewer than 4 samples at once. How should you adapt your pipeline to handle this situation correctly?
hard
A. Use a fixed window size of 1 to avoid buffering
B. Apply the filter on whatever samples arrive, even if fewer than 4, without buffering
C. Discard any samples fewer than 4 and wait for a full batch
D. Process only when at least 4 samples are available; buffer incoming data until then
Solution
Step 1: Understand window size requirement
Moving average with window 4 needs 4 samples to compute an average.
Step 2: Handle fewer samples in real-time
Buffer incoming samples until at least 4 are collected, then apply filter.