python – Functions as arguments to another function

Question:

There is a task:

Write a function composition (f, g) that takes two functions as input, f and g, and returns their composition h (x) = f (g (x)). Define a composition function, assuming that g can have any arguments, and any value returned by g will be a valid argument for f.

How to pass the result of running g to f if f is the argument itself?

This abstraction does not reach me.

PS in the task it is recommended to use closures.

Answer:

Example:

def g(*args):
    return sum(*args)

def f(x):
    return x**2

def composition(f, g):
    def func(*args):
        return f(g(*args))
    return func

Usage example:

In [16]: composition(f, g)([1, 2, 3])
Out[16]: 36

We use the same composition function with other functions:

In [20]: def f2(s):
    ...:     return s[::-1]
    ...:
    ...: def g2(s):
    ...:     return ''.join(s[::2])
    ...:

In [21]: composition(f2, g2)("0123456789")
Out[21]: '86420'
Scroll to Top