Apply a Function N Times

Medium ⏱ 12 min 46% acceptance ★★★★☆ 4.3
Write a function apply_n_times(func, value, n) that applies the single-argument function func to value, repeated n times, feeding each result back in as the next input, and returns the final result. apply_n_times itself must not be a one-liner recursion; use an ordinary loop.

Examples

Example 1
Input
def double(x): return x * 2
apply_n_times(double, 3, 4)
Output
48
Explanation

3 -> 6 -> 12 -> 24 -> 48 after 4 applications of double.

Example 2
Input
apply_n_times(double, 5, 0)
Output
5
Explanation

Zero applications returns the original value unchanged.

Constraints

  • n is a non-negative integer.
  • func takes exactly one argument and returns a value of the same type.

Topics

Functionshigher-order functions

Companies

MetaNetflix

Hints

Hint 1

Use a for loop that runs n times, reassigning value = func(value) each iteration.

Hint 2

If n is 0, the loop body never runs and value is returned unchanged.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.