Skip to content
Exercise · Functions as values · lesson 9 of 10

Exercise: apply n times

Write a function apply_n(func, n) that returns a new function of one argument. The new function applies func to its argument n times in a row and returns the result: apply_n(func, 3)(x) is func(func(func(x))).

  • apply_n(lambda x: x * 2, 3)(1) → 8
  • apply_n(lambda s: s + "a", 2)("b") → "baa"
  • apply_n(lambda x: x * 2, 0)(7) → 7

Constraints: n is an integer from 0 to 20; with n equal to 0, the new function returns its argument unchanged. func takes one argument, and its result can be passed to func again. The returned function can be called many times, and each call starts from its new argument.

Do not add extra imports unless the task says so explicitly.

apply_n.py — python
python · 3 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way