Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Build an Adder Function FactoryE02. Create a Multiplier FactoryE03. Make a Simple Call CounterE

Problem No 3

Make a Simple Call Counter

Easy

6 minute session

Summary

Create a function factory that returns a callable tracking how many times it's been invoked.

Problem statement

Implement make_counter() which returns a function (counter). Each time the returned counter() is called, it should return the number of times it has been called so far (1-based). Use a closure to store and update the count without using global variables or attributes on objects.

Task

Use a closure to maintain internal state (a counter) that persists across calls of the returned function.

Examples

Basic usage

Input

(make_counter())()

Output

1

Explanation

make_counter() returns a function with internal state. Calling it the first time returns 1.

Input format

No external input. Your function make_counter() will be called and its result invoked in tests.

Output format

The returned counter() should produce an integer representing the call count.

Constraints

Do not use global variables. Use a closure (an inner function) and nonlocal variables to store state.

Samples

Sample input 0

(lambda c: (c(), c(), c()))(make_counter())

Sample output 0

(1, 2, 3)

Explanation 0

A fresh counter is created and called 3 times, producing counts 1, 2, 3.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

09:16 AM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.