For performance reasons, please do not use recursion. That would be disastrous.
def fact(n, total=1): while True: if n == 1: return total n, total = n - 1, total * n
Check running results
cProfile.run('fact(126000)')
4 function calls in 5.164 seconds
Using the stack is convenient (for example, a recursive call), but it is expensive: storing detailed information can take up a lot of memory.
If the stack is high, it means that the computer stores a lot of information about function calls.
The method takes up only read-only memory (as an iteration).
Or use for loop
def fact(n): result = 1 for i in range(2, n + 1): result *= i return result
Check running results
cProfile.run('fact(126000)')
4 function calls in 4.708 seconds
Or using the built-in math function
def fact(n): return math.factorial(n)
Check running results
cProfile.run('fact(126000)')
5 function calls in 0.272 seconds
binbjz Mar 29 '18 at 9:50 2018-03-29 09:50
source share