2017-07-07 100 views
0

这是对codewars.com一个挑战,但我想不通,为什么这个while循环不起作用我不知道为什么这个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

请在这里告诉我们一些背景。什么是n?你想用这个功能实现什么? –

+0

n是一个数字,这里是我想要实现的链接https://www.codewars.com/kata/sum-of-digits-slash-digital-root –

回答

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 
+0

谢谢,我感谢你的帮助:) –

0

我很高兴,要更新n,但对于combine。每次迭代结束时可能需要重置?

+0

我真的是#%$ * @! 感谢提示 –

+1

我们都一直在那里,不用担心!这就是为什么编码很有趣。 – CaptainMeow

1

有趣;)

def digital_root(n): 
    return n if n < 10 else digital_root(sum(int(i) for i in str(n))) 
+0

太棒了,我喜欢它^^ –

相关问题