Discuss / Python / 为什么老师说即使把fact(n)函数改成尾递归方式,也会导致栈溢出?

为什么老师说即使把fact(n)函数改成尾递归方式,也会导致栈溢出?

Topic source

fact(n)函数改了也会导致栈溢出,那为何fact-iter函数不会?而且老师给的修改后程序的功能即使只有fact-iter函数也能实现啊,保留fact(n)的目的又是什么呢?请各位大神指点。

同问

最后不是说了吗?python没有针对尾递归进行优化,所以写不写成尾递归其实并没有什么影响,依然会栈溢出的

孤月坤少

#4 Created at ... [Delete] [Delete and Lock User]

def fact(n): return fact_iter(n, 1)

def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product) print(fact(997))

#都会栈溢出

孤月坤少

#5 Created at ... [Delete] [Delete and Lock User]

def fact(n): if n==1: return 1 return n * fact(n - 1) print(fact(998))

##但是尾递归还先溢出了

感谢!

JeffersLi

#7 Created at ... [Delete] [Delete and Lock User]

最大递归次数是可以重新调整的。

import sys sys.setrecursionlimit(1500) # 设置最大次数1500次。


  • 1

Reply