def compose(f, g):
return lambda x:f(g(x))
def thrice(f):
return compose(f, compose(f, f))
def repeated(f, n):
if n == 0:
return identity
else:
return compose(f, repeated(f, n - 1))
def sq(x): return x**2
1) 打印(三次(三次)(sq)(1))
2) 打印(三次(三次(sq)(2))
谁能向我解释为什么第一个函数返回 1 而第二个函数不起作用? 我在想 thrice(thrice)(sq) 会给我 sq∘sq∘..... 27 次,所以 sq(1) 是 1^27=1,对吗? 谢谢。
最佳答案
thrice(thrice)(sq)(x)
是一个增长极快的函数:
thrice(thrice)(sq)(1.0000009)
#2.890634480354213e+52
thrice(thrice)(sq)(1.000001)
#1.9497974384856317e+58
当你将它应用到 float 时,它很快就会溢出:
thrice(thrice)(sq)(1.000006)
# OverflowError: (34, 'Numerical result out of range')
已编辑(感谢@KarlKnechtel)但是,Python 实现了任意精度整数数字。当您将该函数应用于整数(例如,thrice(thrice)(sq)(2)
)时,解释器会计算精确答案,然后尝试打印它,有 40,403,562 位小数,需要大量时间。
关于一段代码的Python解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46137056/