K
K
KaZ1122018-10-30 23:30:31
Python
KaZ112, 2018-10-30 23:30:31

Error: RecursionError: maximum recursion depth exceeded while getting the str of an object, how to fix?

There is this code

lim = int(input("Сколько чисел найти? "))
def afto(lim, x = 0):
    if lim == 0:
        return
    if x ** 2 % 10 ** len(str(x)) == x:
        print(x)
        return afto(lim - 1, x + 1)
    else:
        return afto(lim, x + 1)
afto(lim)

So, it finds the first 8 numbers, and then such an error pops up, what's the problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Web Dentist, 2018-10-31
@kgb_zor

sys.setrecursionlimit(limit)

B
bbkmzzzz, 2018-10-31
@bbkmzzzz

((x**2)%int("1" + "0" * (len(str(x)))) == x):
can be simplified to:
x ** 2 % 10 ** len(str(x )) == x:
Recursion, however. The exit point from the recursion here is one lim == 0, but:
The first condition checks that lim == 0 and exits, excellent
Next, a complex condition, if everything is ok, print x and call ourselves, changing lim and x
if not - CHANGE X and DON'T CHANGE lim - call yourself - pass condition 1, 2 fails again, CHANGE X and DON'T CHANGE lim - call yourself -> and so on up to the maximum depth of the rabbit hole.
if x ** 2 % 10 ** len(str(x)) this condition can still be satisfied for large values ​​of X - do it through loops, not recursion.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question