K2Raygun11 K2Raygun11 - 5 days ago 17
Python Question

Digital Root without loops Python

def digit_sum(n):
'''(int)->number
Returns the sum of all the digits in the given integer, n'''
if n<10:
return n
return n%10 + digit_sum(n//10)

def digital_root(n):
'''(int)->number
Returns the resulting sum of the digits in the given integer until it reaches a single digit number; via digit_sum'''
while n>9:
n=sum(digit_sum(n))
return n




Wrote the code for
digit_sum
and then used recursion to write
digital_root
. However, my professor put a condition that there must not be any loops in any of the two functions. How would I go about this? Any help is appreciated!

Answer

So the idea is that you have to use recursion for the last one as well? In that case, this should do the job:

def digital_root(n):
    if n < 10:
        return n
    return digital_root(digit_sum(n))
Comments