3
votes

I am trying to get the sum of all digits. The only method allowed to solve this question is recursive function. But, the sum is not supposed to exceed 10. For example, if given n is 38, it should return 2. (3+8 = 11, 1+1 =2)

I made the below code. But, it only returns 11. I approached this question in many different ways such as nested if and while loop, but I could not figure it out. Is there any way that I can solve this question using recursive function?

def digit_sum(n):
    if n//10 <= 0: 
        return n%10   
    return digit_sum(n//10) + n%10
5

5 Answers

1
votes

You can use your approach with minor modifications:

def digit_sum(n):
    if n<10:
         return n
    return (digit_sum(n//10) + n%10 - 1) % 9 + 1

Or ignoring the recursion requirement:

def digit_sum(n):
    return n if n<10 else (n-1) % 9 + 1

Or even shorter (thanks @thanasisp):

def digit_sum(n):
    return n and n%9 or 9
1
votes

The problem is the line

return digit_sum(n//10) + n%10

because if the sum of the digits of n//10 and the last digit becomes a number of two digits no one is reducing it. A possible solution is:

return digit_sum(digit_sum(n//10) + n%10)
0
votes

Try this:

def digit_sum(n):
    """ Recursively add the digits of a positive integer until the sum
    becomes a single digit. Return the sum. """

    sum_of_digits = sum(int(digit) for digit in str(n))    
    if sum_of_digits < 10:        
        return sum_of_digits
    else:        
        return digit_sum(sum_of_digits)


>>> digit_sum(38)
2
0
votes

You can do the following:

def digit_sum(n): 
    if n < 10:
        return n    
    return digit_sum(sum(map(int, str(n))))
0
votes

Here is a recursive solution that does not cast to str:

def digit_sum(n):
    def _digit_sum(n):
        if n == 0:
            return n
        return n % 10 + digit_sum(n//10)
    s = _digit_sum(n)
    if s > 9:
        return digit_sum(s)
    return s

some tests:

def test_digit_sum():
    n = 2
    print(n, digit_sum(n))
    assert digit_sum(n) == 2
    n=10
    print(n, digit_sum(n))
    assert digit_sum(n) == 1
    n=143
    print(n, digit_sum(n))
    assert digit_sum(n) == 8
    n=1434
    print(n, digit_sum(n))
    assert digit_sum(n) == 3
    n=143488837772
    print(n, digit_sum(n))
    assert digit_sum(n) == 8         
    print("***all tests pass***")

test_digit_sum()

output:

2 2
10 1
143 8
1434 3
143488837772 8
***all tests pass***