-2

Trying to write a piece of code that will sum the digits of a number. Also I should add that I want the program to keep summing the digits until the sum is only 1 digit.

For example, if you start with 1969, it should first add 1+9+6+9 to get 25. Since the value 25 has more than a single digit, it should repeat the operation to obtain 7 as a final answer.

Was just wondering how I could pull this off and possibly make it recursive as well. This is what I have so far

def sum_digits3(n):
     r = 0
     while n:
         r, n = r + n % 10, n // 10
     return r   
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
Awlooeh
  • 1
  • 1
  • see: [Digital Root without loops](http://stackoverflow.com/q/40875066/6732794) (edit: removed other link) –  Dec 03 '16 at 03:47

2 Answers2

3

Convert back and forth between strings and ints, make use of sum().

>>> def foo(n):
    n = str(n)
    if len(n) == 1:
        return int(n)
    return foo(sum(int(c) for c in n))

>>> foo(1969)
7
>>> 

def foo(n):
    n = str(n)
    if len(n) == 1:
        return int(n)
    return foo(sum(int(c) for c in n))
wwii
  • 23,232
  • 7
  • 37
  • 77
  • @leaf, sorry, copy and pastes from Idle - type it in Idle that way and it works. An Idle feature I could live without. – wwii Dec 03 '16 at 03:46
  • That's fine. But for some reason, its running fine in my IDLE to. I guess your intention is fine :) – Christian Dean Dec 03 '16 at 03:47
1

It is as simple as involving explicitly the recursion.

def sum_digits3(n):
    r = 0
    while n:
        r, n = r + n % 10, n // 10
    if len(str(r))>1:
        return sum_digits3(r)
    return r

But i must admit that i am going to read the links given by suspicious dog. And the answer of wwii is smarter than mine.

keepAlive
  • 6,369
  • 5
  • 24
  • 39