Designing a recursive function that uses digit_sum to calculate the sum of digits

def digit_sum(n):
    if n==0 or n==1:
        return n
    else:
        return n+digit_sum(n-1)

def digital_root(n):

    if n<10:
        return n
    else:
        return digit_sum((n // 10) + n % 10)

I am trying to use digit_sumto calculate the sum of numbers digital_root, can someone help me. I am trying to use a recursive function for digital_root.

Running a file in the Python shell:

digital_root(1969)

This should calculate 1 + 9 + 6 + 9 = 25, while 25 is greater than 10, then he should calculate the sum of his numbers 2 + 5, so that the final answer is 7.

+4
source share
3 answers

To get the last digit of a number (a positive integer), you can calculate modulo:

last_digit = n % 10

The rest of the room (excluding the last place):

rest = (n - last_digit) / 10

This is theoretically enough to break down a number and add numbers:

def sum_digits(n):
    if n < 10:
        return n
    else:
        last_digit = n % 10
        rest = n // 10
        # or using divmod (thanks @warvariuc):
        # rest, last_digit = divmod(n, 10)
        return last_digit + sum_digits(rest)

sum_digits(1969)  # 25

, 10, , :

def sum_sum_digit(n):
    sum_ = sum_digit(n)
    if sum_ < 10:
        return sum_
    else:
        return sum_sum_digit(sum_)

sum_sum_digit(1969) # 7

, , :

def sum_digit(n):
    return sum(map(int, str(n)))
    # or as generator expression:
    # return sum(int(digit) for digit in str(n))
+5

- (for, while), , :

def digital_root(n):
    if n < 10:
        return n
    a, b = divmod(n, 10)
    b += digital_root(a)
    return digital_root(b)

>>> digital_root(1969)
7

:

def digital_root(n):   # n > 0
    return 1+(n-1)%9

>>> digital_root(1969)
7
+2

try it...

digitSum = 0
solution = 0
S = raw_input()
S = list(map(int, S.split()))
#print S
for i in S:
    digitSum += i
#print digitSum
singleDigit = len(str(digitSum)) == 1
if singleDigit == True: solution = digitSum
while singleDigit == False:
    solution = sum( [ int(str(digitSum)[i]) for i in range( 0, len(str(digitSum))) ] )
    digitSum = solution
    singleDigit = len(str(solution)) == 1
print(solution)
+1
source

Source: https://habr.com/ru/post/1661999/


All Articles