Answer the question
In order to leave comments, you need to log in
How to understand recursion in Python?
Greetings
I came across the problem of raising a number to a power through function recursion, but I can not understand the recursion algorithm.
The solution of the problem:
def rec(a,b):
if b == 0:
return 1
else:
return a * rec(a, b-1)
a, b = 2, 3
print(rec(a,b))
Answer the question
In order to leave comments, you need to log in
The unit is returned to the previous function call, where it is multiplied by a equal to two and returned to the previous call again. So until it reaches the first call, which will return the value of its print () function. To better represent this, mentally replace the function calls with its body
(
if 3 == 0:
return 1
else:
return 2 * (
if 2 == 0:
return 1
else:
return 2 * (
if 1 == 0:
return 1
else:
return 2 * (
if 0 == 0:
return 1
else:
#Эта ветка никогда не выполнится
)
)
)
)
Before learning recursion, understand recursion first.
Recursion is a way of solving a problem by simplifying it to the point where the problem can already be taken and solved, and not simplified.
You have already been given an example with a degree:
2 ^ 2
It is known that if we simplify to:
2 ^ 0, then we should get the result 1
So, simplify the task of raising to a power until the current exponent becomes equal to 0.
def pow(num, n2):
1 if n2 == 0 else num * pow(num, n2-1)
And yes, it is useful to think recursively. Don't give up trying to figure it out.
For example, traversing trees is much easier recursively than iteratively.
Also, I recommend reading SICP. This book gives a clear understanding between two nuances about recursion that not every programmer knows about. Example problem : Write a recursive function that calculates the factorial iteratively. Once again I will pay attention to the wording: the function is recursive, but the calculation is iterative! All this is not nonsense and is quite logical, more details in SICP
def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])
print(listsum([1,3,5,7,9]))
And what does python have to do with it?) Recursion is recursion, it's not a bun of any language, it's a mathematical concept. She is the same everywhere. What is the actual problem? The function calls itself. In your case, it will call itself on itself (yes, that sounds so-so), decrementing the variable b (your degree) until the "if b == 0:" test is true.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question