Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compose a function n times in python

I know how to compose two functions by taking two functions as input and output its composition function but how can I return a composition function f(f(...f(x)))? Thanks

def compose2(f, g):
    return lambda x: f(g(x))

def f1(x):
    return x * 2
def f2(x):
    return x + 1

f1_and_f2 = compose2(f1, f2)
f1_and_f2(1)
like image 920
voila Avatar asked Nov 07 '25 16:11

voila


1 Answers

You use a loop, inside a nested function:

def compose(f, n):
    def fn(x):
        for _ in range(n):
            x = f(x)
        return x
    return fn

fn will be have closure that retains references to the f and n that you called compose with.

like image 77
Mad Physicist Avatar answered Nov 09 '25 04:11

Mad Physicist