Medium: Interview Core · Problem 39 of 82

Make a Counter

MediumFunctionsPython

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()())
  1. It prints 1
  2. It prints 0
  3. 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?

  1. Nothing: its variables are deleted
  2. The variables of the outer function that it uses (a closure)
  3. 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.)