python - 数字中所有数字的递归和

标签 python python-3.x recursion return

我被困在这个练习中。

任务:

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/

相关文章:

python - Telegram 对话机器人中后退按钮实现的最佳实践

python - 图像未在 python OpenCV 中打开

python - 数字分解

python - 从函数返回数组索引

javascript - 如何停止 JavaScript 中的递归函数?

python - 尝试在 Qt 中分配无父小部件时的奇怪行为

python - sympy.simplify 不适用于 "tanh^2(x-y) + sech^2(x-y)"

python - 如何将两个列表写入一行的两列到 CSV?

recursion - 递归gmake问题

java - 递归插入时是否会重建二叉搜索树?