1

So I was studying recursion function online. And the one question asks me to write a function to add up a number's digits together. For example (1023) -> 1 + 0 + 2 + 3 = 6. I used % and // get get rid of a digit each time. However, I don't know how to add them up together. The closest I can get is to print out each digit. Can anyone help me solve it or give me a hint please?

def digitalSum(n):
    if n < 10:
        sum_total = n
        print(sum_total)
    else:
        sum_total = n % 10
        digitalSum((n - (n % 10))//10)

        print(sum_total)

digitalSum(1213)
2
  • 1
    sum_total = n % 10? Did you mean sum_total += n % 10? Commented May 21, 2014 at 3:43
  • Since I cannot actually assign a value to sum_total at the beginning, other wise the value will be reassigned to sum_total. So sum_total += n % 10 will cause an error, "local variable 'sum_total' referenced before assignment " Commented May 21, 2014 at 3:49

2 Answers 2

5

Your function should return the current digit plus the sum of the rest of the digits:

def digitalSum(n):
    if n < 10: return n
    return n % 10 + digitalSum(n // 10) 

print digitalSum(1213)

For completeness, you can also handle negative numbers:

def digitalSum(n):
    if n < 0: sign = -1
    else: sign = 1
    n = abs(n)
    if n < 10: return n
    return sign * (n % 10 + digitalSum(n // 10)) 

print digitalSum(1213)
Sign up to request clarification or add additional context in comments.

10 Comments

Thank you for answering. But I was asked to not use any string method.
@Rui, the accepted answer makes use of unnecessary exponent and log calculations and calls to the int function. It is not the preferred method.
@perreal Perhaps not :) But it was more of an exercise in recursion writing than the actual Math. In fact playing around with your answer leads me to several issues. I'm not sure either either of our answers handles all edge cases :)
@JamesMills, I really don't like the use of exponents and log for this sort of problem. Can you point out an issue with my answer?
Yeah there are at least three ways to interpret negative numbers and their respective sum of digits!
|
0

A correct version of your function is as follows:

from math import log10


def sum_digits(n, i=None):
    if i is None:
        i = int(log10(abs(n)))

    e = float(10**i)
    a, b = (n / e), (abs(n) % e)

    if i == 0:
        return int(a)
    else:
        return int(a) + sum_digits(b, (i - 1))


print sum_digits(1234)
print sum_digits(-1234)

Example:

$ python -i foo.py
10
8
>>>

Updated: Updated to properly (IHMO) cope with negative numbers. e.g: -1234 == -1 + 2 + 3 + 4 == 8

NB: Whilst this answer has been accepted (Thank you) I really think that perreal's answer should have been accepted for simplicity and clarity.

Also note: that whilst my solution handles negative numbers and summing their respective digits, perreal clearly points out in our comments that there are ate least three different ways to interpret the summing of digits of a negative number.

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.