New course! Every coder should learn Generative AI!
Try a free lesson+ 2
as a result, we reach the base case where n = 0. and we return on the outgoing top:
the base case was executed, the if branch was executed, and the function returned the fac (0) value to the previous function fac (1), i.e., one
f(0)=1 - base case
f(1)=f(0) * 1
f(1)=1*1
...
1. fac(3) => fac(2) * 3
2. fac(2) => fac(1) * 2
3. fac(1) => 1
4. fac(0) =>1
5. 1 * 2 - return to call fac(2)
6. 2 * 3 - return to call fac(3)
+ 1
Base case mean the termination condition for the recursive program
(n-1) may means calling recursive function by reducing 1
+ 1
Hi! the base case is an expression at the beginning of a function (or program) where you explicitly specify a value. in this case, what is n. this value is usually written to the condition of the branch operator if
a value in parentheses means that a program or function will take one from the base value
+ 1
search Google or YouTube for recursion on the python. this is difficult to explain in the text. its easier to imagine it graphically, visually
+ 1
I will try to explain in general terms: recursion refers to algorithms that go through all degrees of nesting, to full depth. for example, we need to calculate the factorial of the number (3!) factorial of the number 3 is calculated using the formula: 3! = 1* 1 * 2 * 3. lets create a program:
program formula 3! = 1 * (3-2) * (3-1) * 3
n! = 1 * (n-2) * (n-1) * n
that is, each previous factor is less by one than the next.
+ 1
def fac(n):
if n == 0:
return 1
return fac(n-1) * n
print(fac(3))
+ 1
at the beginning of the program (inside the function) we create a base case in which we specify the factorial value explicitly. i.e. we set him a specific value of 1 and move on
+ 1
return fac(n-1) * n - in this line, we write the formula for calculating the factorial and ask you to return the result
print(fac(3)) - print the result by calling the fac function with a value of 3
+ 1
def fac(3):
[since we have n is not equal to 0, we skip the if branch and hit the line:]
return fac(n-1)*n
+ 1
return fac(3-1)*3
fac(2)*3
we put the number 3 in the formula at the very end and see that we still need to know what the value of fuc (2) is. we do not know it, so the program returns to the very beginning and again calls itself, but already with the value def fac (2)
+ 1
the action of the line of code with the value fac(2) * 3 is still suspended and put aside... the program waits for the fac(2) value to be known to substitute the real digit
+ 1
n = 2 again n is not 0, hence if is skipped again and n with value 2 is substituted into the formula:
return fac(2-1)*2
fac(1)*2
+ 1
https://www.sololearn.com/post/206034/?ref=app
0
Cool
0
Sarah Jonas you also didnt know what recursion was?