4
votes

I need to write a code that counts the sum of the digits of a number, these is the exact text of the problem:The digital sum of a number n is the sum of its digits. Write a recursive function digitalSum(n) that takes a positive integer n and returns its digital sum. For example, digitalSum(2019) should return 12 because 2+0+1+9=12. These is the code I wrote :

def digitalSum(n):
   L=[] 
   if n < 10:
      return n
   else:
      S=str(n)
      for i in S:
         L.append(int(i))
      return sum(L)

These code works fine, but it's not a recursive function, and I'm not allowed to change any int to str. May you help me?

10

10 Answers

10
votes

Try this:

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

Edit: The logic behind this algorithm is that for every call of the recursive function, we chop off the number's last digit and add it to the sum. First we obtain the last digit with n % 10 and then we call the function again, passing the number with the last digit truncated: n // 10. We only stop when we reach a one-digit number. After we stop, the sum of the digits is computed in reverse order, as the recursive calls return.

Example for the number 12345 :

5 + digitalSum( 1234 )
5 + 4 + digitalSum( 123 )
5 + 4 + 3 + digitalSum( 12 )
5 + 4 + 3 + 2 + 1 <- done recursing
5 + 4 + 3 + 3
5 + 4 + 6
5 + 10
15
3
votes

It's homework, so I'm not writing much code. Recursion can be used in the following way:

  • get the first (or last) digit
  • format the rest as a shorter number
  • add the digit and the digital sum of the shorter number (recursion!)
3
votes

This is more of a question related to algorithms.

Here is your answer:

def digit_sum(a):
    if a == 0:
        return 0
    return a % 10 + digit_sum(a/10)

Let me know if you don't understand why it works and I'll provide an explanation.

1
votes

Some hints:

  1. You can define inner functions in Python
  2. You can use the modulus operator (look up its syntax and usage) to good effect, here
  3. There's no need to build up an explicit list representation with a proper recursive solution

EDIT The above is a bit "bad" as a general answer, what if someone else has this problem in a non-homework context? Then Stack Overflow fails ...

So, here's how I would implement it, and you need to decide whether or not you should continue reading. :)

def digitalSum(n):
  def process(n, sum):
    if n < 10:
      return sum + n
    return process(n / 10, sum + n % 10)
  return process(n, 0)

This might be a bit too much, but even in a learning situation having access to one answer can be instructive.

My solution is more a verbose than some, but it's also more friendly towards a tail call optimizing compiler, which I think is a feature.

0
votes
def digital_sum(number):
    if number < 10: 
        return number
    else:
        return number % 10 + digital_sum(number / 10) 
0
votes
def sumofdigits(a):
    a = str(a)
    a = list(a)
    b = []
    for i in a:
        b.append(int(i))
        b = sum(b)
    if b > 9:
        return  sumofdigits(b)
    else:
        return b
print sumofdigits(5487123456789087654)
0
votes

For people looking non-recursive ways,

Solution 1: Using formula,

digits = int(input())
res = (digits * (digits + 1) // 2)

Solution 2: Using basic syntax

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

total = numbers[0]
print(f'{total}')
for val in numbers[1:]:
    print(f'{total} + {val} = {total + val}')
    total += val

gives

6
6 + 5 = 11
11 + 3 = 14
14 + 8 = 22
22 + 4 = 26
26 + 2 = 28
28 + 5 = 33
33 + 4 = 37
37 + 11 = 48
-1
votes

Still you can do it in O(log10 n)...cancel out all the digits that adds to 9 then if no numbers left,9 is the answer else sum up all the left out digits...

def rec_sum_Reduce(n) : ans = 0 for i in map(int,str(n)) : ans = 1+(ans+i-1)%9 return ans

-2
votes

def drs_f(p):

 drs = sum([int (q) for q in str(p)])
 while drs >= 10:
     drs = sum([int(q) for q in str(drs)])
return drs
-3
votes
def digitalSum(n):
   if n < 10:
      return n
   else:
      return ???

The 1st part is from your existing code. The ??? is the part you need to work out. It could take one digit off n and add it to the digitalSum of the remaining digits.

You don't really need the else, but I left it there so the code structure looks the same