K2Raygun11 K2Raygun11 - 1 year ago 153
Python Question

Digital Root without loops Python

def digit_sum(n):
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):
Returns the resulting sum of the digits in the given integer until it reaches a single digit number; via digit_sum'''
while n>9:
return n

Wrote the code for
and then used recursion to write
. 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 Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download