Home  >  Article  >  Backend Development  >  How many times can recursion be reached in python?

How many times can recursion be reached in python?

高洛峰
高洛峰Original
2016-10-20 09:39:401557browse

How many times can recursion be reached in python? Because when running the program, the number of times is sometimes more and sometimes less. I have never thought about this problem before. Then verify it yourself. The code is as follows:

def recursion(n):
    if(n <= 0):
        return
    print n
    recursion(n - 1)
  
if __name__ == "__main__":
    recursion(1000)

When I run the above code on my own machine, I find that it can print up to 998, and then the "RuntimeError: maximum recursion depth exceeded" error will be thrown. Hey, there are limits. But then I thought about it, python wouldn't be so weak. After some searching, I found that this is a mechanism specially set up by Python to prevent infinite recursion from causing Python to overflow and crash. The maximum number of recursions can be readjusted. (http://docs.python.org/2/library/sys.html#sys.setrecursionlimit), modify the code as follows:

import sys
sys.setrecursionlimit(1500)  # set the maximum depth as 1500
  
def recursion(n):
    if(n <= 0):
        return
    print n
    recursion(n - 1)
  
if __name__ == "__main__":
    recursion(1200)


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn