Comprehensions: Generators
Description
Practice generator expressions — comprehensions without the brackets,
passed directly into a reducer that consumes them lazily.
Two patterns to internalize:
1. `func(expr for x in xs if cond)` — pass the gen-exp as a sole
argument and the parentheses can be elided. Use with sum / any /
all / max / min.
2. `next((expr for x in xs if cond), default)` — find-first with a
safe default. The default is critical; without it, an empty match
raises StopIteration.
Traps worth knowing:
- `all([])` is True (vacuous truth). `any([])` is False.
- `max([])` raises; use `max(..., default=0)`.
- `next(gen)` with no default raises on empty.
Coverage map:
generator + sum/any/all/max total_squared, any_negative,
all_positive, max_word_length
next(gen, default) find-first first_negative, first_key_with_value Constraints
- Solve each prompt in a single expression where possible. - Inputs may be empty; handle the empty case via the reducer's default argument or next()'s default — NOT a conditional. - Don't import anything; everything here is plain builtins.
solution.py
output
Run the cases to see results here.