2017-07-07 96 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

太棒了,我喜歡它^^ –