Search code examples
pythonrecursionrecursionerror

RecursionError: maximum recursion depth exceeded in comparison - sys.setrecursionlimit(1500)


I am doing a Python exercise using recursion. The goal is to request which maximum value the user wants to study and to test all the values from 1 to this maximum value. The algorithm always reachs 1 or 4. The program stops when those values are reached and then returns one of those values.

I wanted to use a recursive approach here but I have an issue with the maximum recursion depth.

The program only works for numbers 1 and 2 :

C:\Users\Mathieu\Desktop
λ python algo.py
Enter a number > 0 1
vect1 =  [1]
vect4 =  []

C:\Users\Mathieu\Desktop
λ python algo.py
Enter a number > 0 2
vect1 =  [1]
vect4 =  [2]

I have founded suggestions asking to extend the maximum recursion depth that I have extented to 1500 but that is still not working.

[Previous line repeated 996 more times]

RecursionError: maximum recursion depth exceeded in comparison

I have also tried iterative approach but I have issue :

  def recursive(s, n):
        while n != 0:
            s = s + (n % 10)**2
            n = n // 10
        if s == 1 or s == 4:
            return s
        else:
            return recursive(s, n)

Would you have any advices or tips ? Thank you in advance

import sys
sys.setrecursionlimit(1500)

class Error(Exception):
    """ Base class for exceptions """
    pass

class StrictlypPositive(Error):
    """ Called when the number is lower than 1 """
    pass

def recursive(s, n):
    if s == 1 or s == 4:
        return s
    else:
        s = s + (n % 10)**2
        n = n // 10
        return recursive(s, n)

vect1 = []
vect4 = []

while True:
    try:
        maxVal = int(input("Enter a number > 0 ").strip('n'))
        if maxVal < 1:
            raise StrictlypPositive
        break
    except ValueError:
        print("Enter a number")
    except StrictlypPositive:
        print("Enter a number strictly positive")

for val in range(1, maxVal + 1):
    theSum = 0
    theSum = recursive(theSum, val)
    if theSum == 1:
        vect1.append(val)
    else:
        vect4.append(val)

print("vect1 = ", vect1)
print("vect4 = ", vect4)

Solution

  • Adding a simple print in the recursive function reveals an endless loop.

    Enter a number > 0: 3
    recurse: s 1, n 0
    recurse: s 4, n 0
    recurse: s 9, n 0
    recurse: s 9, n 0
    recurse: s 9, n 0
    recurse: s 9, n 0
    recurse: s 9, n 0
    recurse: s 9, n 0
    recurse: s 9, n 0
    recurse: s 9, n 0
    

    It's not clear what the calculation should properly produce, but having it not recurse when the new values are identical to the old values should at least avoid the immediate symptom.

    In the general case, when code doesn't do what you expect, add a print where you think it's going wrong, and see what it does.