def digital_root(n):
x = str(n)
while len(x)!=0 and len(x)!=1:
r = 0
for i in range(len(x)):
r= r + int(x[i])
x = str(r)
return r
A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.
My code:
Is this code efficient? I get the following error:
Traceback (most recent call last):
File "main.py", line 8, in <module>
test.assert_equals( digital_root(0), 0 )
File "/home/codewarrior/solution.py", line 8, in digital_root
return r
UnboundLocalError: local variable 'r' referenced before assignment