Skip to content Skip to sidebar Skip to footer

RECURSIVE Function That Will Sum Digits Of Input

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 examp

Solution 1:

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))

Solution 2:

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.


Post a Comment for "RECURSIVE Function That Will Sum Digits Of Input"