1. Initial recursion
Recursive function: Call the function itself within a function.
Maximum depth of recursion: 998
As you just saw, the recursive function will continue to execute if it is not blocked by external forces. But we have already talked about the problem of function calls before. Each function call will generate a name space of its own. If it is called continuously, it will cause the name space to occupy too much memory, so Python is trying to prevent this kind of phenomenon. , forcibly controlling the number of recursion levels to 997 (as long as 997! You can’t suffer losses or be fooled...).
What can be used to prove this "998 theory"? Here we can do an experiment:
def foo(n): print(n) n += 1 foo(n) foo(1)
From this we can see that the maximum number that can be seen before an error is reported is 998. Of course, 997 is a number set by python for the memory optimization of our program. Default value, of course we can also modify it through some means:
import sys print(sys.setrecursionlimit(100000))
We can modify the maximum depth of recursion in this way. We just set the recursion depth allowed by python to 10w. As for the actual recursion depth, it can be reached The depth depends on the performance of the computer. However, we still do not recommend changing this default recursion depth, because if the problem cannot be solved with 997 levels of recursion, it is either not suitable to use recursion to solve it, or your code is too poorly written~~~
Look At this point, you may feel that recursion is not such a good thing, and it is not as useful as while True! However, there is a saying circulating in the world: humans understand cycles, gods understand recursion. So don’t underestimate recursive functions. Many people have been blocked from the threshold of great masters for so many years because they failed to understand the true meaning of recursion. And many of the algorithms we learn in the future will be related to recursion. Come on, only if you learn it will you have the capital to dislike it!
2. Recursive example explanation
Here we will give another example to illustrate what recursion can do.
Example 1:
Now you ask me, how old is Mr. Alex? I said I won't tell you, but Alex is two years older than egon.
If you want to know how old Alex is, do you still have to ask Egon? egon said, I won’t tell you either, but I am two years older than Sir Wu.
You asked Sir Wu again, but Sir Wu didn’t tell you either. He said he was two years older than Taibai.
Then you ask Taibai, Taibai will tell you that he is 18.
Did you know it at this time? How old is alex?
1 | jinxin | 18 |
---|---|---|
武 sir | 20 | |
egon | 22 | |
alex | 24 |