Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Build a Resettable Counter Factory

Create a closure-based counter factory that produces stateful counter functions which can be reset or reconfigured.

Python practice25 minClosures & Function FactoriesAdvancedLast updated April 13, 2026

Problem statement

Write a function factory make_counter(start=0, step=1) that returns a stateful function counter(). The returned counter should: - Return the next value in a sequence each time it's called. The sequence starts at start and increments by step on each call (first call returns start). - Expose a method counter.reset(new_start=None) which resets the counter's next-return value to the original start value. If new_start is provided, it should set the start to new_start and reset to that value. - Expose a method counter.set_step(new_step) which updates the increment step used for subsequent calls. Design the closure so all state (current next value, step, and original start) is captured by the returned function and its helper methods. Avoid using global variables or classes; implement using closures and function attributes.

Task

Implement make_counter(start=0, step=1) that returns a callable counter which remembers and updates its internal state, and exposes methods to reset and change the step.

Examples

Basic usage

Input

c = make_counter() (c(), c(), c())

Output

(0, 1, 2)

Default start=0, step=1. Calls return 0, then 1, then 2.

Using reset and set_step

Input

c = make_counter(3, 2) (c(), c(), c.reset(), c(), c.set_step(5), c())

Output

(3, 5, None, 3, None, 8)

Starts at 3 with step 2: returns 3 then 5. reset() returns None and resets back to 3. Next call returns 3. set_step(5) returns None; next call returns 8 (3 + 5).

Input format

Each test expression will be evaluated after your implementation. Use make_counter(...) to construct counters within a single expression.

Output format

Return values from expressions are compared as their string representation. Tests may evaluate tuples containing numbers and None.

Constraints

Implement make_counter using closures (no classes, no global mutable state). The returned counter must be a callable with methods reset(...) and set_step(...). Methods may return None.

Samples

Sample 1

Input

c = make_counter(5, 2) (c(), c())

Output

(5, 7)

A counter starting at 5 increments by 2 each call: 5 then 7.