🐍 Python for Everyone

← Back to practice bank

Chapter 17 Coding Challenges 55-70 min, auto-graded

Coding Challenges: Generators, Iterators & Context Managers

8 HackerRank-style challenges, auto-graded right in your browser — no setup required. Write your function in the code box, then click Run Tests to check it against a set of test cases (including edge cases). Stuck? Every challenge has a Show Solution reveal at the bottom. Only uses what Chapters 1-17 have covered so far — including yield, generator functions, generator expressions, and the context-manager protocol (__enter__/__exit__). No import beyond math/datetime/random/csv.

How grading works Your code runs entirely in your browser using Pyodide (Python compiled to WebAssembly) — nothing is uploaded anywhere. Keep the function name in the stub exactly as given, since the grader calls it by name.
Why every challenge returns a plain value, not an object The auto-grader compares your function's return value to a JSON-safe expected value (a number, string, boolean, list, or dict) — it can't compare a generator or a custom context-manager instance directly. So every challenge here asks you to build a generator function, a custom iterator class, or a custom context manager class inside your function to actually solve the problem lazily or with guaranteed cleanup, but the function itself always returns a plain number, string, boolean, list, or dict once it has fully driven that generator/iterator/context manager to completion — exactly what a real caller elsewhere in a program would want back, without needing to know anything about the machinery you used internally to compute it. There's no real filesystem in this browser sandbox either, so any "file-like" challenge takes the file's content as a plain string argument instead of touching an actual file.

1 Manual Iterator Walk Easy

Write a function walk_countdown(start) that builds a Countdown class internally with __init__(self, start) storing self.current = start, an __iter__(self) returning self, and a __next__(self) that raises StopIteration once self.current < 0, otherwise returns the current value and decrements it by 1. Get an iterator with it = iter(Countdown(start)), then manually call next(it) in a loop (no for loop), catching StopIteration yourself to know when to stop, collecting every value into a list in order. Return that list.

Constraints: start is always a non-negative integer, including 0.
Examples:
walk_countdown(3) → [3, 2, 1, 0]
walk_countdown(0) → [0]
challenge_1.py
Show Solution
solution_1.py
def walk_countdown(start):
    class Countdown:
        def __init__(self, start):
            self.current = start

        def __iter__(self):
            return self

        def __next__(self):
            if self.current < 0:
                raise StopIteration
            value = self.current
            self.current -= 1
            return value

    it = iter(Countdown(start))
    values = []
    while True:
        try:
            values.append(next(it))
        except StopIteration:
            break
    return values

2 First N Multiples Easy

Write a function first_n_multiples(n, count) that defines a generator function multiples_of(n) using yield to lazily produce n, 2 * n, 3 * n, and so on forever (an infinite generator, since it never has a natural stopping point). Create gen = multiples_of(n), then call next(gen) exactly count times, collecting each result into a list, and return that list — showing that a generator can represent an infinite sequence safely, since the caller (not the generator) decides how many values to actually pull.

Constraints: n is always a positive integer; count may be 0, in which case return an empty list.
Examples:
first_n_multiples(3, 4) → [3, 6, 9, 12]
first_n_multiples(7, 0) → []
challenge_2.py
Show Solution
solution_2.py
def first_n_multiples(n, count):
    def multiples_of(n):
        current = n
        while True:
            yield current
            current += n

    gen = multiples_of(n)
    result = []
    for _ in range(count):
        result.append(next(gen))
    return result

3 First N Values Above a Threshold Medium

Write a function first_n_above(values, threshold, count) that defines a generator function above_threshold(values, threshold) using yield to lazily produce only the entries in values that are greater than threshold, in order. Create gen = above_threshold(values, threshold), then call next(gen) up to count times inside a try/except StopIteration block (stopping early and returning whatever was collected so far if the generator runs out before reaching count values), collecting each result into a list, and return that list.

Constraints: values may be empty; there may be fewer than count matching values, in which case return only however many were actually found.
Examples:
first_n_above([5, 12, 3, 18, 25, 7, 30], 10, 3) → [12, 18, 25]
first_n_above([1, 2, 3], 10, 5) → []
challenge_3.py
Show Solution
solution_3.py
def first_n_above(values, threshold, count):
    def above_threshold(values, threshold):
        for v in values:
            if v > threshold:
                yield v

    gen = above_threshold(values, threshold)
    result = []
    try:
        for _ in range(count):
            result.append(next(gen))
    except StopIteration:
        pass
    return result

4 Sum of Squares via Generator Expression Easy

Write a function sum_of_squares_over(n) that returns sum(i * i for i in range(1, n + 1)) — using a generator expression directly inside sum() rather than building a list first, so no intermediate list of squares is ever created in memory.

Constraints: n is always a non-negative integer; n = 0 means the range is empty, so the sum is 0.
Examples:
sum_of_squares_over(3) → 14 (1 + 4 + 9)
sum_of_squares_over(0) → 0
challenge_4.py
Show Solution
solution_4.py
def sum_of_squares_over(n):
    return sum(i * i for i in range(1, n + 1))

5 Any Divisible By, Short-Circuited Easy

Write a function any_divisible_by(numbers, divisor) that returns False immediately if divisor == 0 (avoiding a division-by-zero error), otherwise returns any(n % divisor == 0 for n in numbers) — using a generator expression so any() can stop checking the instant it finds a match, without ever computing the remainder for every remaining number.

Constraints: numbers may be empty, in which case return False; divisor may be 0.
Examples:
any_divisible_by([1, 3, 5, 8], 2) → true
any_divisible_by([1, 3, 5, 7], 2) → false
challenge_5.py
Show Solution
solution_5.py
def any_divisible_by(numbers, divisor):
    if divisor == 0:
        return False
    return any(n % divisor == 0 for n in numbers)

6 Context Manager Call Tracker Medium

Write a function run_with_tracker(times) that builds a CallTracker class internally with __init__(self) storing self.enters = 0 and self.exits = 0, an __enter__(self) that increments self.enters and returns self, and an __exit__(self, exc_type, exc_value, traceback) that increments self.exits and returns False. Create tracker = CallTracker(), then use with tracker: (an empty block) exactly times times in a row, reusing the same instance every time. Return {"enters": tracker.enters, "exits": tracker.exits}.

Constraints: times is always a non-negative integer, including 0 (meaning the with block never runs at all).
Examples:
run_with_tracker(3) → {"enters": 3, "exits": 3}
run_with_tracker(0) → {"enters": 0, "exits": 0}
challenge_6.py
Show Solution
solution_6.py
def run_with_tracker(times):
    class CallTracker:
        def __init__(self):
            self.enters = 0
            self.exits = 0

        def __enter__(self):
            self.enters += 1
            return self

        def __exit__(self, exc_type, exc_value, traceback):
            self.exits += 1
            return False

    tracker = CallTracker()
    for _ in range(times):
        with tracker:
            pass
    return {"enters": tracker.enters, "exits": tracker.exits}

7 Process With an Error-Suppressing Context Manager Medium

Write a function process_with_error_log(items) that builds an ErrorLogger class internally with __init__(self) storing self.errors = [], an __enter__(self) that returns self, and an __exit__(self, exc_type, exc_value, traceback) that, if exc_type is not None, appends str(exc_value) to self.errors and returns True (suppressing the exception so the loop below keeps going), otherwise returns False. Create logger = ErrorLogger(), then for each item in items, use with logger: around code that raises ValueError("cannot process zero") if item == 0, otherwise appends 100 // item to a results list. Return {"results": results, "errors": logger.errors}.

Constraints: items may be empty; every non-zero item is a positive integer that divides evenly into 100 // item.
Examples:
process_with_error_log([1, 2, 0, 4]) → {"results": [100, 50, 25], "errors": ["cannot process zero"]}
process_with_error_log([]) → {"results": [], "errors": []}
challenge_7.py
Show Solution
solution_7.py
def process_with_error_log(items):
    class ErrorLogger:
        def __init__(self):
            self.errors = []

        def __enter__(self):
            return self

        def __exit__(self, exc_type, exc_value, traceback):
            if exc_type is not None:
                self.errors.append(str(exc_value))
                return True
            return False

    logger = ErrorLogger()
    results = []
    for item in items:
        with logger:
            if item == 0:
                raise ValueError("cannot process zero")
            results.append(100 // item)
    return {"results": results, "errors": logger.errors}

8 Streaming Text Search With Guaranteed Cleanup Medium

Write a function count_matching_lines(text, keyword) that builds a TextSource class internally with __init__(self, text) storing self.text = text and self.opened = False, an __enter__(self) that sets self.opened = True and returns self, and an __exit__(self, exc_type, exc_value, traceback) that sets self.opened = False and returns False — standing in for a real file's guaranteed-cleanup behavior, since this browser sandbox has no real filesystem. Also define a generator function matching_lines(text, keyword) that uses yield to lazily produce each stripped line of text (split on "\n") that contains keyword. Use with TextSource(text) as source: inside the function, and inside that block build matches = list(matching_lines(source.text, keyword)). Return {"matches": matches, "count": len(matches)}.

Constraints: text may be an empty string; keyword may match zero, one, or many lines.
Examples:
count_matching_lines("INFO: ok\nERROR: disk full\nINFO: ready\nERROR: timeout", "ERROR") → {"matches": ["ERROR: disk full", "ERROR: timeout"], "count": 2}
count_matching_lines("", "x") → {"matches": [], "count": 0}
challenge_8.py
Show Solution
solution_8.py
def count_matching_lines(text, keyword):
    class TextSource:
        def __init__(self, text):
            self.text = text
            self.opened = False

        def __enter__(self):
            self.opened = True
            return self

        def __exit__(self, exc_type, exc_value, traceback):
            self.opened = False
            return False

    def matching_lines(text, keyword):
        for line in text.split("\n"):
            if keyword in line:
                yield line.strip()

    with TextSource(text) as source:
        matches = list(matching_lines(source.text, keyword))
    return {"matches": matches, "count": len(matches)}
← Practice Bank Interview Questions →