chessguy
chessguy

Reputation: 165

With a recursive function : RecursionError: maximum recursion depth exceeded while getting the str of an object

def sum_digits(n):

    if n < 0:
        raise ValueError("The number must be higher or equal to 0")
    
    num = sum([int(i) for i in str(n)])
    
    if str(num) == 1:
        return num
    else:
        return sum_digits(num)

If I try print(sum_digits(854)), I got the following error:

RecursionError: maximum recursion depth exceeded while getting the str of an object

I tried to step into that code, but for me that code is perfectly legit. What's wrong with that code?

Upvotes: 0

Views: 1318

Answers (3)

Zombo
Zombo

Reputation: 1

Here are some other approaches to that code. First, iterative style:

def sum_digits(n_in):
   n_out = 0
   for s_chr in str(n_in):
      n_out += int(s_chr)
   return n_out
n = sum_digits(854)
print(n)

then functional style:

from functools import reduce
n_sum = reduce(lambda n_ca, s_it: n_ca + int(s_it), str(854), 0)
print(n)

Upvotes: 0

Diptangsu Goswami
Diptangsu Goswami

Reputation: 5965

Your code is always evaluating to False and recursively calling the function.

>>> n = 1
>>> str(n) == 1
False

Change it to

if num == 1:
    return num
else:
    return sum_digits(num)

Upvotes: 2

Dr. V
Dr. V

Reputation: 1914

This is never true:

str(num) == 1

why not just

num == 1

And it still doesn't work. If you enter with 4, it will stay 4 and never get one. Maybe make the condition num < 10 ... depending on what you want to achieve.

Upvotes: 1

Related Questions