我被困在这个练习中。
任务:
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.
这是它的工作原理:
数字根(16)
1 + 6 = 7
数字根(942)
9 + 4 + 2 = 15 ... 1 + 5 =6
我的方法在这里。关于如何正确返回正确值的任何提示?如果有任何帮助,我将不胜感激。
def digital_root(n):
answ = 0
s = 0
x = str(n)
for i in range(0, len(x)):
s = s + int(x[i])
if len(str(s)) > 1:
digital_root(s)
elif len(str(s)) == 1:
answ = s # here is an answer
return answ # answer is 2 but this one is not returning 2, why?
return answ # here it returns answ=0, I want to return 2...
print(digital_root(493193))
最佳答案
你怎么看这个:
def digital_root(n):
if n<10 :
return n
return digital_root( n%10 + digital_root( n//10 ) )
关于python - 数字中所有数字的递归和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61233330/