S2Q1 · Count Strings with Length Divisible by 3 or 5¶
⚡ Quick Reference
Function: count_strings_length_divisible_by_3_or_5(strings: list) -> int
Core idea: count strings where len(s) % 3 == 0 or len(s) % 5 == 0.
def count_strings_length_divisible_by_3_or_5(strings: list) -> int:
return sum(1 for s in strings if len(s) % 3 == 0 or len(s) % 5 == 0)
Key rules:
- Divisible by 3 OR 5 - either condition counts
- Strings divisible by both (e.g. length 15) are counted once
- sum(1 for ...) counts without building an intermediate list
Problem Statement¶
Problem
Write a function count_strings_length_divisible_by_3_or_5(strings) that counts how many strings in the list have a length divisible by 3 or 5.
Example:
["misunderstanding", "inconsiderately", "characters", "computers"]
3
Tracing the example¶
| String | Length | % 3 |
% 5 |
Divisible? | Count? |
|---|---|---|---|---|---|
"misunderstanding" |
16 | 1 ❌ | 1 ❌ | ❌ | ❌ |
"inconsiderately" |
15 | 0 ✅ | 0 ✅ | ✅ (both) | ✅ |
"characters" |
10 | 1 ❌ | 0 ✅ | ✅ | ✅ |
"computers" |
9 | 0 ✅ | 4 ❌ | ✅ | ✅ |
Count = 3 ✓
Solution approaches¶
Key takeaways¶
OR - count if divisible by 3, 5, or both
Using or means strings with lengths divisible by both 3 and 5 (like 15, 30) are counted exactly once - not twice. or is the correct operator here, not two separate checks.
sum(1 for ...) - count without a list
sum(1 for s in strings if condition) counts matching elements using a generator - no intermediate list is created. Equivalent to len([s for s in strings if condition]) but more memory-efficient.
sum(map(bool_func, iterable)) - boolean counting
Python's sum() treats True as 1 and False as 0. Mapping a boolean function over a list and summing the results is an elegant way to count how many elements satisfy a condition.