1

I'm trying to return the count of digits in a number using recursion like this: DigitCount(3456) → 4. The code that I have without using recursion works fine, which is:

    def DigitCount(n)
        return len(str(n))

But when I try using recursion in this way:

    def DigitCount(n):
        return len(str(DigitCount(n)))

I get an error message saying 'RecursionError: maximum recursion depth exceeded'

1
  • 1
    this is an infinite loop! Commented Nov 14, 2015 at 21:36

3 Answers 3

2

The problem with your recursive function is that you didn't specify a base case to end the recursion, producing an infinite loop that ends with a stack overflow.

When writing recursive procedures, you have to think how to make the problem smaller at each call (in this case, dividing by 10 does the trick) until you reach a point where the problem is so simple, that you already know the answer - for instance, a number less than 10 has a single digit. Try this:

def DigitCount(n):
    if n < 10:
        return 1
    else:
        return 1 + DigitCount(n / 10) # use n // 10 in Python 3.x

It works as expected, as long as n is greater than or equal to zero:

DigitCount(0)
=> 1
DigitCount(234)
=> 3
Sign up to request clarification or add additional context in comments.

Comments

1

What about something like:

def DigitCount(n):
    if n<10: return 1
    return 1 + DigitCount(n//10)

The idea is:

  • a number smaller than 10 has length 1
  • a number greater than 10 has length 1 + length(n//10); for instance 456 has length 1 + length(45).

Comments

1

It can be done using strings also.

def digitCount(n):
    if len(str(n)) == 1:
        return 1
    else:
        return 1 + digitCount(str(n)[1:])

It's a bit dirty, and very inefficient but works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.