gpt4 book ai didi

python - 如何在python中编写n次函数

转载 作者:行者123 更新时间:2023-11-28 20:30:02 26 4
gpt4 key购买 nike

我知道如何通过将两个函数作为输入并输出其组合函数来组合两个函数,但如何返回组合函数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)

最佳答案

在嵌套函数中使用循环:

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

fn 将有一个闭包,它保留对您调用 composefn 的引用。

关于python - 如何在python中编写n次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58850623/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com