AP CSP Day 36: List Traversal & Filtering | Cycle 2
Share
Filtering algorithms can fail silently when the condition is inverted, collecting the wrong elements without producing an obvious error. A filter that should collect values greater than a threshold may accidentally collect values less than or equal to it if the comparison operator is reversed. AP CSP Cycle 2 list traversal questions present filtering pseudocode and ask students to determine which elements appear in the result list, or to identify the logic error that causes the result to differ from the stated goal. Testing with a concrete small list is the most reliable verification strategy.
📚 Study the Concept First (Optional) Click to expand ▼
Filtering Bugs: Wrong Condition
Inverted Filter
The most common filtering bug inverts the condition, collecting elements that should be excluded and excluding elements that should be collected. If the intended filter is 'keep values greater than 10' but the code uses 'less than 10', the result list contains exactly the wrong elements.
Missing Initialization
A filtering procedure that forgets to create an empty result list before the loop will fail. The append operation requires an existing list to append to.
Practice Question
Consider the following code:
scores ← [88, 92, 75, 95, 81, 90]
count ← 0
FOR EACH score IN scores
{
IF score ≥ 90
{
count ← count + 1
}
}
DISPLAY(count)Which of the following changes would cause the displayed value to be DIFFERENT from the original?
I. Changing the condition to score > 90
II. Changing the condition to score ≥ 85
III. Reversing the order of elements in scores
Original (score ≥ 90): 92, 95, 90 pass → count = 3. Change I (score > 90): 92, 95 pass (90 is excluded) → count = 2 (different). Change II (score ≥ 85): 88, 92, 95, 90 pass → count = 4 (different). Change III (reverse order): same elements, same count = 3 (no change).
B) Change II also produces a different result, not just change I. C) Change III does not affect the count because all elements are still checked regardless of order. D) Change III has no effect on the final count.
Students think reversing list order changes the count. FOR EACH visits every element regardless of order, so the count of elements meeting a condition is the same in any order.
FOR EACH always processes every element. Changing the order of elements affects the order of processing but not which elements satisfy a condition or how many do.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help