Skip to content

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:

Input
["misunderstanding", "inconsiderately", "characters", "computers"]
Output
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

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)
def count_strings_length_divisible_by_3_or_5(strings: list) -> int:
    count = 0
    for s in strings:
        length = len(s)
        if length % 3 == 0 or length % 5 == 0:
            count += 1
    return count
def count_strings_length_divisible_by_3_or_5(strings: list) -> int:
    return len(list(filter(
        lambda s: len(s) % 3 == 0 or len(s) % 5 == 0,
        strings
    )))
def count_strings_length_divisible_by_3_or_5(strings: list) -> int:
    is_valid = lambda s: len(s) % 3 == 0 or len(s) % 5 == 0
    return sum(map(is_valid, strings))

map(is_valid, strings) produces a sequence of True/False values. sum() treats True as 1 and False as 0 - a clean way to count booleans.


Key takeaways

01

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.

02

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.

03

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.