Write a parameterised Python decorator @repeat(n) that calls a function n times — three levels of nested functions explained, with live tests.
The problem
Write a decorator factory repeat(times) so that
@repeat(3)
def hello():
print("Hello")
hello()
prints Hello three times. The wrapped function should return the result of its last call and keep its __name__.
Examples
Example 1
Input
captured(say_hello, repeat)
Expected output
'Hello\nHello\nHello\n'
Example 2
Input
returns_and_name(repeat)
Expected output
(10, 'double')
+ 1 hidden test on Submit.
Edge cases to ask about
- times = 1
- Return value
- Name preserved
How the tests call your code
These helpers run before your code. The test inputs above call them.
def say_hello(repeat): @repeat(3) def hello(): print("Hello") hello() def returns_and_name(repeat): @repeat(2) def double(x): return x * 2 return (double(5), double.__name__)
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Three nested functions | O(times) | O(1) | factory(args) → decorator(func) → wrapper(*args). |
Walkthrough of the optimal approach (try it yourself first)
@repeat(3) means hello = repeat(3)(hello). So repeat(times) must return a decorator, which takes func and returns a wrapper. Three nested functions, each closing over the variable it needs.
Keep functools.wraps on the innermost wrapper and return the last result.
Complexity: O(times) time, O(1) space. The wrapped function is called `times` times.
Reveal the reference solution
import functools def repeat(times): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): result = None for _ in range(times): result = func(*args, **kwargs) return result return wrapper return decorator
Follow-ups interviewers ask
- Make @repeat work with or without parentheses.
- Write it as a class-based decorator.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Decorator With Arguments (@repeat(n)) in Python?
The optimal solution runs in O(times) time and O(1) auxiliary space. The wrapped function is called times times.
What follow-up questions do interviewers ask about Decorator With Arguments (@repeat(n))?
Make @repeat work with or without parentheses. Write it as a class-based decorator.
