Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Digital sum, Python

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?

like image 319
Reginald Avatar asked Dec 21 '22 17:12

Reginald


2 Answers

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
like image 90
Grampa Avatar answered Jan 06 '23 00:01

Grampa


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!)
like image 20
Lev Levitsky Avatar answered Jan 05 '23 23:01

Lev Levitsky