一个数中所有数字的递归和

2024-05-23 17:47:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我被困在这个练习中

任务:

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))

Tags: oftheinnumberlenreturnisroot
3条回答

你对此有何看法:

def digital_root(n):
    if n<10 :
         return n
    return digital_root( n%10 + digital_root( n//10 ) )

这是我的看法。我很想使用sum,但这几乎像是作弊,因为你可以直接使用sum([int(i) for i in str(n)])

def digital_root(n):
    # convert to a string
    as_str = str(n)

    # get the value of the current first digit
    value = int(as_str[0])

    if len(as_str) > 1:
        # add the recursive return plus the value
        # for anything other than our base case.
        # pass the rest of the digits into our recursive call
        return digital_root(int(as_str[1:])) + value

    # our base case
    return value

print(digital_root(493193))

主要的问题是,在执行递归调用时,没有将返回值赋给任何对象,因此对于需要多次传递的任何值,都会得到0

另外,在递归调用之后,长度应该是1,因此下面的elif是不必要的,并且将导致不正确的返回值,因为它不会将s赋值给answ

固定版本:

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:
       s = digital_root(s)
    answ = s # You could even return s directly
    return answ

print(digital_root(493193))

相关问题 更多 >