Counter Factory Using a Closure

Hard ⏱ 18 min 31% acceptance ★★★★★ 4.9
Write a function make_counter(start=0) that returns a new function increment(step=1). Each call to the returned increment function should add step to an internal counter (initialized to start) and return the new counter value. The counter state must persist between calls via a closure, not a global variable.

Examples

Example 1
Input
c = make_counter()
c()
c()
c(5)
Output
1, 2, 7
Explanation

First two calls default step=1 (1, then 2), third call adds 5 (7).

Constraints

  • Do not use global or a mutable default argument to store state.
  • Each call to make_counter() must produce an independent counter.

Topics

Functionsclosures

Companies

MetaAdobeAtlassian

Hints

Hint 1

Use the nonlocal keyword inside the inner function to modify the outer variable.

Hint 2

The outer function defines the state variable; the inner function closes over it and is returned.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.