Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Return Multiple Closure Functions Sharing One State

Create a factory that returns several functions which all capture and mutate the same enclosed state.

Python practice25 minClosures & Function FactoriesAdvancedLast updated April 13, 2026

Problem statement

Write a function factory make_counter(initial=0) that returns four functions which share the same enclosed counter state: - get(): returns the current counter value. - inc(n=1): increments the counter by n and returns the new value. - dec(n=1): decrements the counter by n and returns the new value. - set(value): sets the counter to value and returns the new value. All four functions must be closures that capture the same mutable state so that calls to inc/dec/set affect subsequent get calls. Multiple calls to make_counter must produce independent counters (each call has its own state). The implementation should not use global variables.

Task

Implement a function factory that returns multiple callable closures (get, inc, dec, set) that share a single mutable state. Ensure each returned function updates or reads the shared state correctly and different factory instances are independent.

Examples

Basic increment and read

Input

(lambda f: (f[0](), f[1](3), f[0]()))(make_counter(2))

Output

(2, 5, 5)

make_counter(2) returns (get, inc, dec, set). We call get() -> 2, inc(3) -> 5, then get() again -> 5.

Input format

A single expression will be evaluated that calls make_counter(...) and the returned functions.

Output format

The expression should evaluate to a value (int, tuple, etc.) which will be compared as a string.

Constraints

Do not use global variables. The returned functions must be closures over a shared mutable state. All numeric inputs will be integers.

Samples

Sample 1

Input

(lambda f: (f[0](), f[1](), f[0]()))(make_counter(3))

Output

(3, 4, 4)

Start at 3. get()->3, inc() defaults to +1 -> 4, get()->4.