0
can anyone explain me this recursion program?
2 Respostas
+ 5
In Python, we know that a function can call other functions. It is even possible for the function to call itself. These types of constructs are termed as recursive functions.
Following is an example of a recursive function to find the factorial of an integer.
I choose the simplest example to realize you the flow of the program. Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 3 (denoted as 3!) is 1*2*3 = 6.
py.code:
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
#Output: The factorial of 3 is 6
In the above example, factorial() is a recursive function as it calls itself. When we call this function with a positive integer, it will recursively call itself by decreasing the number.
Each function multiplies the number with the factorial of the number below it until it is equal to one. This recursive call can be explained in the following steps.
factorial(3) # 1st call with 3
3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3 * 2 * 1 # return from 3rd call as number=1
3 * 2 # return from 2nd call
6 # return from 1st call
In your code the process is below:
fun(6)
= 6 + fun(5)
= 6 +(5 + fun(4))
= 6 + (5 + (4 + fun(3)))
= 6+ (5 + (4 + (3 + fun(2))
= 6+ (5 + (4 + (3 + (2 + fun(1))
= 6+ (5 + (4 + (3 + (2 + (1 + fun(0))
= 6+5+4+3+2+1+0 = 21
Coined by: https://www.programiz.com/python-programming/recursion
+ 4
fun(6)
= 6 + fun(5)
= 6 +(5 + fun(4))
= 6 + (5 + (4 + fun(3)))
.
.
= 6 + 5 + 4 + 3 + 2 + (1 + fun(0)) # base case reached
= 6+5+4+3+2+1+0 = 21
Also you are printing the result at every call.