我看过几个使用 while True
循环来实现 Python 尾调用优化的例子。例如:
def tail_exp(base, exponent, acc=1):
if exponent == 0:
return acc
return tail_exp(base, exponent - 1, acc * base)
变成
def tail_exp_2(base, exponent, acc=1):
while True:
if exponent == 0:
return acc
exponent, acc = exponent - 1, acc * base
我很想知道这种技术是否适用于所有或大多数Python中的递归算法,以及在优化递归算法时需要注意哪些缺陷或“坑”?
tail_exp_2
并没有使用递归...因此并不存在真正的尾调用优化。 - undefined