RecursionError: maximum recursion depth exceeded in comparison in Python

Dung Do Tien Aug 15 2021 192

Hello Everyone, I have a small project with Python 3.8.2 and I have created a method to help find numbers with recursive as below:

def find_number(n):
  if n == 0 or n == 1:
    return 1
  else :
    return (n * find_number(n-1))  
 
print("Factorial is :", find_number(10))

It works very well for me and returns 3628800. But when I set the param value to 1000 I got the error RecursionError: maximum recursion depth exceeded in comparison

print("Factorial is :", find_number(1000))
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    print("Factorial is :", find_number(1000))
  File "main.py", line 5, in find_number
    return (n * find_number(n-1))  
  File "main.py", line 5, in find_number
    return (n * find_number(n-1))  
  File "main.py", line 5, in find_number
    return (n * find_number(n-1))  
  [Previous line repeated 995 more times]
  File "main.py", line 2, in find_number
    if n == 0 or n == 1:
RecursionError: maximum recursion depth exceeded in comparison

I still do not understand why it occurs. How can I fix it?

Have 2 answer(s) found.
  • J

    Jair Rojas Garcia Aug 15 2021

    I think the best practice to avoid this error is to use other loops instead of recursion. Like:

    def find_number(n):
      num = 1
      for i in range(2, n + 1):
        num = num * i
      return num
     
    print("Factorial is :", find_number(1000))

    It works very well for me.

  • G

    Giang Nguyen Aug 15 2021

    You can use sys.setrecursionlimit() function to help increase the max number for recursive:

    import sys
    sys.setrecursionlimit(2000)
    
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close