Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Designing a recursive function that uses digit_sum to calculate 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_sum to calculate the sum of digits of digital_root can someone help me please. I am trying to use a recursive function for digital_root.

Running the file in Python shell:

digital_root(1969)

This should calculate 1+9+6+9=25 then since 25 is greater than 10 it should then calculate the sum of its digits 2+5 so that the final answer is 7.

like image 643
Garret Ulrich Avatar asked Feb 05 '23 15:02

Garret Ulrich


1 Answers

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

last_digit = n % 10

The remainder of the number (excluding the last place) is:

rest = (n - last_digit) / 10

This should in theory be enough to split a number and add the digits:

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

If you want to apply this recursivly until you have a value smaller than 10 you just need to call this function as long as that condition is not fulfilled:

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

Just if you're interested another way to calculate the sum of the digits is by converting the number to a string and then adding each character of the string:

def sum_digit(n):
    return sum(map(int, str(n)))
    # or as generator expression:
    # return sum(int(digit) for digit in str(n))
like image 75
MSeifert Avatar answered Feb 08 '23 04:02

MSeifert