一个数中所有数字的递归和 [英] recursive sum of all the digits in a number

查看:51
本文介绍了一个数中所有数字的递归和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在这个练习中.

任务:

数字根是数字中所有数字的递归和.给定 n,取 n 的数字之和.如果该值超过一位,则继续以这种方式减少,直到产生一位数.这仅适用于自然数.

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.

这是它的工作原理:

digital_root(16)
1 + 6 = 7

digital_root(16)
1 + 6 = 7

digital_root(942)
9 + 4 + 2 = 15 ... 1 + 5 =6

digital_root(942)
9 + 4 + 2 = 15 ... 1 + 5 =6

我的方法在这里.关于如何正确返回正确值的任何提示?我将不胜感激.

My approach is here. Any tips on how to properly return correct value? I would appreciate any help.

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

推荐答案

主要问题是,在进行递归调用时,您没有将返回值分配给任何东西,因此对于任何值,您总是会得到 0这需要不止一次通过.

The main problem is that, when doing the recursive calls, you're not assigning the return value to anything, so you'll always get 0 for any value that requires more than one pass.

此外,在递归调用之后,长度应该是 1,所以下面的 elif 不是必需的,并且会导致不正确的返回值,因为它不会分配 s回答

Also, after the recursive call, the length should be 1 so the following elif is not necessary and will cause incorrect return values since it won't be assigning s to 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))

这篇关于一个数中所有数字的递归和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆