我被困在这个练习中
任务:
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))
你对此有何看法:
这是我的看法。我很想使用
sum
,但这几乎像是作弊,因为你可以直接使用sum([int(i) for i in str(n)])
主要的问题是,在执行递归调用时,没有将返回值赋给任何对象,因此对于需要多次传递的任何值,都会得到0
另外,在递归调用之后,长度应该是1,因此下面的
elif
是不必要的,并且将导致不正确的返回值,因为它不会将s
赋值给answ
固定版本:
相关问题 更多 >
编程相关推荐