Bird
0
0

The following code tries to implement a sliding window sum but has a bug. What is the error?

medium📝 Debug Q14 of 15
Rest API - Rate Limiting and Throttling
The following code tries to implement a sliding window sum but has a bug. What is the error?
data = [2, 4, 6, 8]
window_size = 2
result = []
for i in range(len(data) - window_size):
    window_sum = sum(data[i:i+window_size])
    result.append(window_sum)
print(result)
AThe result list is not initialized.
BThe sum function is used incorrectly.
CThe loop range misses the last window, causing incomplete results.
DWindow size is larger than data length.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the loop range

    The loop runs from 0 to len(data) - window_size - 1, which is 4 - 2 - 1 = 1, so only indices 0 and 1.
  2. Step 2: Identify missing last window

    The last valid window starts at index 2 (data[2:4]), but the loop excludes it because it should run to len(data) - window_size + 1.
  3. Final Answer:

    The loop range misses the last window, causing incomplete results. -> Option C
  4. Quick Check:

    Loop range must cover all windows [OK]
Quick Trick: Use range(len(data) - window_size + 1) for full coverage [OK]
Common Mistakes:
  • Using wrong loop range causing missed windows
  • Misusing sum function
  • Not initializing result list

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes