Mathematica 有一个方便的 Nest
用于重复计算 f(f(f(f(...f(n)))))
的函数。不是你每天都需要的东西,但偶尔有用。这是一个简单的实现:
def nest(f, expr, n):
assert n >= 0
if n == 0:
return expr
else:
return f(nest(f, expr, n - 1))
>>> nest(lambda x: (1 + x) ** 2, 1, 3)
676
有Pythonic的方法可以做到这一点吗?
最佳答案
也许如果你喜欢这些东西,你可以看看 functools.reduce
:
from functools import reduce
def nest(f, expr, n):
return reduce(lambda x, _: f(x), range(n), expr)
>>> nest(lambda x: (1 + x) ** 2, 1, 3)
676
关于python - Python有像Mathematica一样的 `nest`函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65345098/