Search code examples
pythonrecursionrecursionerror

Using recursion to reduce digits of a number


I am working through a coding challenge and I'm using this problem as a way to get myself used to recursion. The problem gives me an integer n that is of any length and my job is to sum all the digits until it becomes a single digit number and then output the number of times that took place.

To illustrate, lets just say the value is 87559:

8+7+5+5+9 = 34
3 + 4 = 7

So the return value is 2. If n was 1,000,000, the return would be 1.

I felt like this was a recursion problem so I tried to get that part working first. This is my code:

def digitDegree(n):
    
    return digitDegree(sum(map(int, str(n)))

However, this is the error:

Traceback (most recent call last):
  main.py3 in the pre-written template, in getUserOutputs
    userOutput = _runlnlao(testInputs[i])
  main.py3 in the pre-written template, in _runlnlao
    return digitDegree(*_fArgs_qeqrszlgdnyi)
  main.py3 on line 13, in digitDegree
    return digitDegree(sum(map(int, str(n))))
  main.py3 on line 13, in digitDegree
    return digitDegree(sum(map(int, str(n))))
  main.py3 on line 13, in digitDegree
    return digitDegree(sum(map(int, str(n))))
  [Previous line repeated 9993 more times]
RecursionError: maximum recursion depth exceeded while getting the str of an object

Solution

  • This is why you always start with the base cases: you have to stop the recursion somewhere. Back up to your basics on recursion:

    • How do you know when you're done?
    • What do you return in that base case?
    • When you transition from a recursion step back to its parent, what information do you need to accumulate?

    Those three items will get you to the solution.

    Coding is left as an exercise for the student. :-)