繁体   English   中英

我不知道为什么while循环不会停止迭代

[英]I don't know why this while loop doesn't stop iterating

这在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

有趣;)

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

很高兴您要更新n ,但是combine又如何呢? 也许在每次迭代结束时都需要重置吗?

我将执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM