出于性能原因,请不要使用递归。那将是灾难性的。
def fact(n, total=1):
while True:
if n == 1:
return total
n, total = n - 1, total * n
检查运行结果
cProfile.run('fact(126000)')
4 function calls in 5.164 seconds
使用堆栈很方便(就像递归调用),但它需要付出代价:存储详细信息可能会占用大量内存。
如果堆栈较高,则表示计算机存储了大量有关函数调用的信息。
该方法只占用常量内存(如迭代)。
或者使用“for”循环
def fact(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
检查运行结果
cProfile。运行(‘事实(126000)’)
4 function calls in 4.708 seconds
或者使用内置函数math
def fact(n):
return math.factorial(n)
检查运行结果
cProfile。运行(‘事实(126000)’)
5 function calls in 0.272 seconds