这对codewars.com来说是一个挑战,但我无法弄清楚为什么这个while循环不起作用
def digital_root(n):
# Creating variable combine to have the sum
combine = 0
# as long as n is more than two numbers.
while n > 10:
# converting n to string to iterate
for i in str(n):
# getting the sum each element in n
combine += int(i)
# reset n to be equal to the combined result
n = combine
return combine
此外,任何解决方案都将受到赞赏,这里是挑战的链接 https://www.codewars.com/kata/sum-of-digits-slash-digital-root
答案 0 :(得分:1)
有趣;)
def digital_root(n):
return n if n < 10 else digital_root(sum(int(i) for i in str(n)))
答案 1 :(得分:0)
很高兴您正在更新n
,但combine
呢?也许在每次迭代结束时都需要重置?
答案 2 :(得分:0)
我会做以下事情:
def digital_root(n):
combined = 0
while True:
for i in str(n):
combined += int(i)
print combined
# this is the condition to check if you should stop
if len(str(combined)) < 2:
return combined
else:
n = combined
combined = 0
编辑:您也可以在不转换为str
的情况下执行此操作:
def digital_root(n):
combined = 0
while True:
for i in str(n):
combined += int(i)
print combined
if combined < 10:
return combined
else:
n = combined
combined = 0