我知道如何通过将两个函数作为输入并输出其组合函数来组合两个函数,但是如何返回组合函数 f(f(... f(x)))?谢谢
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)
答案 0 :(得分:5)
您可以在嵌套函数内部使用循环:
def compose(f, n):
def fn(x):
for _ in range(n):
x = f(x)
return x
return fn
fn
将具有闭包,保留对您调用f
的{{1}}和n
的引用。
答案 1 :(得分:1)
如果要使其成为一行,
然后尝试一下
def f1(x):
return x * 2
def f2(x):
return x + 1
>>> out = lambda x, f=f1, f2=f2: f1(f2(x)) # a directly passing your input(1) with 2 function as an input (f1, f2) with default so you dont need to pass it as an arguments
>>> out(1)
4
>>>
>>> def compose(f1, n):
... def func(x):
... while n:
... x = f1(x)
... n = n-1
... return x
... return func
>>> d = compose(f1, 2)
>>> d(2)
8
>>> d(1)
4
>>>
答案 2 :(得分:1)
请注意,这大多只是从https://stackoverflow.com/a/16739439/2750819复制而来,但是我想弄清楚如何将它应用于任何一个函数n次。
def compose (*functions):
def inner(arg):
for f in reversed(functions):
arg = f(arg)
return arg
return inner
n = 10
def square (x):
return x ** 2
square_n = [square] * n
composed = compose(*square_n)
composed(2)
输出
179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216
答案 3 :(得分:0)
您可以使用functools.reduce
:
from functools import reduce
def compose(f1, f2):
return f2(f1)
reduce(compose, [1, f2, f1]) # f1(f2(1))
输出:
4
如果要编写相同的函数n次:
n = 4
reduce(compose, [1, *[f1]*n]) # f1(f1(f1(f1(1))))
输出:
16