Loop Over a List and Count Matches in Python
Scenario
Test count_open_rooms(seat_counts) in Python on empty, single-item, and mixed lists.
def count_open_rooms(seat_counts: list[int]) -> int:
open_rooms = 0
for seats in seat_counts:
if seats > 0:
open_rooms += 1
return open_rooms
assert count_open_rooms([]) == 0
assert count_open_rooms([1]) == 1
assert count_open_rooms([0, 2, 0, 1]) == 2Try it yourself
Compare each fixture input to verify Python returns the exact expected count.
| Case | Result |
|---|---|
| count_open_rooms([]) | Select a choice above to see what happens. |
| count_open_rooms([1]) | Select a choice above to see what happens. |
| count_open_rooms([0, 2, 0, 1]) | Select a choice above to see what happens. |
Reveal the explanation
- count_open_rooms([])
0 — loop runs 0 times and returns initialized open_rooms = 0.
- count_open_rooms([1])
1 — single last-seat room counts as open.
- count_open_rooms([0, 2, 0, 1])
2 — counts rooms with 2 and 1 seats, ignores zeros.
Keep return aligned with the def body, not indented inside the for loop, and test empty [] before moving to multi-item lists.
Download shared test cases
Your turn
Write count_passing(scores) in Python using a for loop and add 3 assert lines for [], [60], and [59, 60, 85].
Common mistake Indenting return inside the for loop.
Check your work
assert count_passing([]) == 0; assert count_passing([60]) == 1; assert count_passing([59, 60, 85]) == 2.
Quick check
This browser could not save your progress. Changes last until you leave the page.