import sys
num = long(raw_input("Enter the number for the factorial -> "))
sys.setrecursionlimit(num + 1)
def fact(n):
if n == 0 or n == 1:
return 1
else:
return (n * fact(n - 1))
print fact(long(num))
以上是我用于查找阶乘的代码,由于最大递归限制深度为'997',我尝试使用以下方法更改: -
import sys
sys.setrecursionlimit()
但它仍然会出错。我还能做什么?
答案 0 :(得分:3)
调用帧也很重要。对于fact(10)
,您需要 11 帧。传入long
整数会导致一些额外的工作进一步下线,需要另一个帧。在计数中添加两个:
sys.setrecursionlimit(num + 2)
如果您有其他框架调用调用fact()
函数的代码,请添加更多内容。请注意,首先在输入上调用long()
是没有意义的;如果需要,Python将自动生成long
对象。
那就是说,我不会贬低递归限制。将其设置为高值一次,或许,但不要继续调整它。
更好的想法是不使用递归:
def fact(n):
num = 1
while n > 1:
num *= n
n -= 1
return num
或更好的是,不要重新发明轮子并使用math.factorial()
代替。从Python 3.2开始,Python实现使用binary split factorial algorithm(加上前21个左右的结果表)。
答案 1 :(得分:0)
import sys
num = long(raw_input("Enter the number for the factorial -> "))
sys.setrecursionlimit(num + 1)
def fact(n):
if n == 0 or n == 1:
return 1
else:
return (n * fact(n - 1))
print
print "Factorial is -> ", fact(int(num))
这完美无缺,我们可以增加限制> 997