Compose Two Functions

Medium ⏱ 12 min 60% acceptance ★★★★★ 4.9
Write a function compose(f, g) that returns a new function h such that h(x) == f(g(x)) for any x. This is standard function composition: apply g first, then f to its result.

Examples

Example 1
Input
def add_one(x): return x + 1
def square(x): return x * x
h = compose(square, add_one)
h(3)
Output
16
Explanation

g=add_one is applied first: 3+1=4, then f=square: 4*4=16.

Constraints

  • f and g each take exactly one argument.
  • compose must return a callable, not a computed value.

Topics

Functionsfirst-class functions

Companies

GoogleAdobe

Hints

Hint 1

Define an inner function that takes x, calls g(x) first, then passes that result into f.

Hint 2

Return the inner function without calling it.

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