我有以下代码失败,出现以下错误:
RuntimeError:超出最大递归深度
我试图重写它以允许尾递归优化(TCO).我相信如果发生TCO,这段代码应该是成功的.
def trisum(n, csum):
if n == 0:
return csum
else:
return trisum(n - 1, csum + n)
print(trisum(1000, 0))
Run Code Online (Sandbox Code Playgroud)
我是否应该断定Python不执行任何类型的TCO,或者我只是需要以不同的方式定义它?
一时兴起,我最近测试了这两种方法timeit,看看哪种评估方法更快:
import timeit
"""Test method returns True if either argument is falsey, else False."""
def and_chk((a, b)):
if not (a and b):
return True
return False
def not_or_chk((a, b)):
if not a or not b:
return True
return False
Run Code Online (Sandbox Code Playgroud)
......并得到了这些结果:
VALUES FOR a,b -> 0,0 0,1 1,0 1,1
method
and_chk(a,b) 0.95559 0.98646 0.95138 0.98788
not_or_chk(a,b) 0.96804 1.07323 0.96015 1.05874
...seconds per 1,111,111 cycles.
Run Code Online (Sandbox Code Playgroud)
效率的差异在1%到9%之间,总是有利于if not (a and b),这与我的预期相反,因为我理解if not a or not b它将按顺序评估其术语(if …
python if-statement micro-optimization logical-operators python-2.7
您能举例说明何时何何不使用Lambda?我的书给了我一些例子,但它们令人困惑.