15. Counter with a Closure
Difficulty: Easy · Topic: Functions & decorators
Write make_counter(start=0, step=1). It returns a function; each call of that function returns the next number: start on the first call, then start + step, and so on.
Every counter is independent: two counters made by make_counter never affect each other. Do not use global variables.
Your code runs in CPython on our servers against 4 tests, including hidden ones.
Sample test
c = make_counter()
[c(), c(), c()]Expected: [0, 1, 2]
Hints
Hint 1
A function defined inside another can read the outer function's variables: that is a closure.Hint 2
To assign to an outer variable, declare itnonlocal first.Hint 3
Return the current value, then advance it.Learn the concepts
- Functions, *args, **kwargs and closures · 8 min read. Every kind of parameter, closures that remember state, nonlocal and late binding.
More Python problems
- A Logging Decorator That Keeps Metadata · Easy
- Memoize a Function · Medium
- Time Every Call · Medium
- Retry with Backoff · Hard
- Rate Limiter Decorator · Hard