Make a Counter
Write make_counter(start=0, step=1) that returns a function. Each time you call that function it returns the next number: first start, then start + step, then start + 2 * step, and so on.
Two counters made by separate calls to make_counter must be independent.
Understand the problem
Predict what happens with a naive attempt.
What happens when this runs?
def make():
n = 0
def inc():
n += 1
return n
return inc
print(make()())
- It prints
1 - It prints
0 - It raises
UnboundLocalError
Assigning to n inside inc makes n a local variable of inc, so n += 1 reads a local that has no value yet. To change the variable of the enclosing function you must declare it nonlocal n.
What does the inner function keep alive after make_counter has returned?
- Nothing: its variables are deleted
- The variables of the outer function that it uses (a closure)
- The whole module
A closure keeps the enclosing variables the inner function uses. Each call to make_counter creates new variables, which is why two counters do not interfere.
Write the solution
Return the inner function.
def make_counter(start=0, step=1):
# Write your code here.
pass
Hint 1: a question to ask yourself
Where does the current value live between calls? Which keyword lets the inner function change it?
Hint 2: the shape of the answer
Store the next value in a variable of the outer function. The inner function returns it and then adds the step, using nonlocal.
Reflect
Solution
def make_counter(start=0, step=1):
value = start
def counter():
nonlocal value
current = value
value += step
return current
return counter
Another way: a generator and next()
def make_counter(start=0, step=1):
def numbers():
value = start
while True:
yield value
value += step
return numbers().__next__
Another way: itertools.count
from itertools import count
def make_counter(start=0, step=1):
return count(start, step).__next__
What this tests: closures, nonlocal, functions returning functions, and independent state.
How a closure works: the inner function carries references to the outer variables it uses. make_counter can end; value lives on, owned by that one counter function.
nonlocal versus global: nonlocal rebinds a variable of an enclosing function; global rebinds a module variable. Reading a variable needs neither; only assigning does.
A class would also work (__call__ and an attribute). Closures are the lighter tool when there is just one piece of state.
What an interviewer might ask next: Add a reset() ability. How? (Attach a second function, or return an object with two methods; a class is cleaner then.)
VISIBLE = 3
CASES = [
('c = make_counter()\nresult = [c(), c(), c()]', [0, 1, 2], 'the default counter'),
('c = make_counter(10, 5)\nresult = [c(), c(), c()]', [10, 15, 20], 'a start and a step'),
('a = make_counter()\nb = make_counter()\na()\na()\nresult = (a(), b())', (2, 0), 'two independent counters'),
('c = make_counter(step=-1)\nresult = [c(), c(), c()]', [0, -1, -2], 'counting down'),
('c = make_counter(5)\nresult = callable(c)', True, 'it returns a function'),
('c = make_counter(1, 0)\nresult = [c(), c()]', [1, 1], 'a step of zero'),
]