Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Produce a Sequence Generator via Closure

Build a function factory that returns a callable sequence generator using closures to retain state.

Python practice15 minClosures & Function FactoriesIntermediateLast updated April 13, 2026

Problem statement

Write a function factory make_sequence(start=0, step=1) that produces a sequence generator function using a closure. The returned function takes no arguments and, on each call, returns the next value in an arithmetic progression beginning at start and increasing by step. Requirements: - The first call to the returned function should return start. - Each subsequent call should return the previous value plus step. - Multiple generators created by separate calls to make_sequence must maintain independent internal state. - start and step may be integers or floats. step may be zero or negative. Do not use global variables. Use a closure (and nonlocal) to preserve state between calls.

Task

Implement make_sequence(start=0, step=1) which returns a zero-argument function that yields the next value in the arithmetic sequence each time it's called.

Examples

Basic integer sequence

Input

g = make_sequence(0, 1) (g(), g(), g())

Output

(0, 1, 2)

g starts at 0 and increments by 1 each call; the three calls return 0, 1, 2.

Independent generators

Input

a = make_sequence(1, 1) b = make_sequence(100, -10) (a(), b(), a(), b())

Output

(1, 100, 2, 90)

a and b each maintain their own state; calls interleave correctly.

Input format

You will implement: make_sequence(start=0, step=1) -> function() The test harness will call make_sequence and then call the returned function(s).

Output format

The sequence-generator function returns the next numeric value (int or float) each time it is called.

Constraints

- Do not use global variables. - start and step are numeric (int or float). - Implementation must use a closure to retain the sequence state. - The returned function must take no parameters.

Samples

Sample 1

Input

g = make_sequence(5, 10) g()

Output

5

First call returns the start value 5.