"""Đây là hàm tính giai thừa của
một số nguyên by TipsMake.com"""
if n == 1:
return 1
else:
return (n * giaithua(n-1))
num = 5
num1 = int(input("Nhập số cần tính giai thừa: "))
print("Giai thừa của", num, "là", giaithua(num))
print("Giai thừa của", num1, "là", giaithua(num1))
In the above example, look at the definition of the function giaithua(n)
, in the if . else statement, the giaithua(n)
function giaithua(n)
has called itself again. Run the above code and get the following result:
When calling the function giaithua(n)
with a positive integer, it will call recursively by decreasing the number. Each time the function is called, it multiplies the number with the factorial of 1 until the number equals 1. This recursive call can be explained in the following steps:
giaithua (4) # The first call with 4
4 * giaithua (3) # Second call with 3
4 * 3 * giaithua (2) # The third call with 2
4 * 3 * 2 * giaithua (1) # The fourth call with 1
4 * 3 * 2 * 1 # Returned from call 4 when number = 1
4 * 3 * 2 # Returned from call 3
4 * 6 # Return from call 2
24 # Returns from the first call
The recursion ends when the number drops to 1. This is called the base condition. Each recursive function must have a basic condition to stop recursion or it will become an infinite function, calling itself to it.
Each recursive function calls itself stored on memory. Therefore, it consumes more memory than traditional functions. Python will stop calling the function after 1000 calls. If you run the code below:
def giaithua(n):
"""Đây là hàm tính giai thừa của
một số nguyên by TipsMake.com"""
if n == 1:
return 1
else:
return (n * giaithua(n-1))
print (giaithua(1001))
Will receive an error message:
RecursionError: maximum recursion depth exceeded in comparison
This problem can be solved by adjusting the number of recursive calls, as follows:
import sys
sys.setrecursionlimit(5000)
def giaithua(n):
"""Đây là hàm tính giai thừa của
một số nguyên by TipsMake.com"""
if n == 1:
return 1
else:
return (n * giaithua(n-1))
print (giaithua(1001))
But remember, there is still an input limit for factorial functions. For this reason, you should use recursion wisely. To calculate factorial, recursion is not the best solution, for other issues such as directory traversing (traversing a directory), recursion is a good solution.
Python recursive lesson stops here. In the next lesson, we will learn about the Python / Anonymous function / Python function, so don't miss it.
Do not forget to store your Python files.
Next lesson: Anonymous function, Lambda in Python
Previous post: Python function parameter