1

I have written a function in python 2.7 that caluclates the digit sum of a given number:

def dig_sum(n):
    s = 0
    while n:
         s = s + n % 10
         n = n/10
    return s

and now tries to rewrite it as a recursive function:

def dig_sum(n):
    s = 0
    if n != 0:
        s = n % 10
        s += s
        return dig_sum(n/10)
    return s

What is wrong with my recursive function? And what is best practice when doing such functions? Thanks in advance!

3
  • The in-place addition on s does not propagate to the outer functions - you always return 0 Commented Sep 24, 2014 at 19:35
  • You've gotten some good answers for your question which is great! But in the future, when you begin asking more complicated questions, you'll get better results if you describe the problem you're having better. You simply asked "What's wrong with my function?" instead of describing any errors, exceptions, or bad results you got. Try to always include these details in your questions. Commented Sep 24, 2014 at 19:38
  • Bear in mind if you run this on a number with more than 1000 digits it will crash. Recursion in Python is usually to be avoided unless your code is significantly more complicated without it (otherwise it's just for CS wonks). Commented Sep 24, 2014 at 20:04

2 Answers 2

5

The recursive function would look like this

def dig_sum(n):
    if n < 10:                       # Handle single digits as your base case
        return n
    else:
        return n%10 + dig_sum(n/10)  # Add one's digit, then shift and continue

Testing

>>> dig_sum(1001)
2

>>> dig_sum(12345)
15
Sign up to request clarification or add additional context in comments.

Comments

2
def dig_sum(n):
    if n != 0:
        s = n % 10
        return s + dig_sum(n/10)
    else:
        return 0

print dig_sum(45)

Output

9

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.