不明白为什么数字和的代码不起作用

时间:2021-01-11 23:45:33

标签: python

我尝试解决代码战数字总和/数字根问题,您必须这样做:

<块引用>

给定n,取n的数字之和。如果该值超过一位,则继续以这种方式减少,直到产生一位数。输入将是一个非负整数。

所以通过 52 会返回 7,因为 5 + 2 是 7,通过 942 会返回 6,因为 9 + 4 + 2 = 15 然后 1 + 5 = 6。

我想出了这个代码:

def digital_root(n):
    n_str = str(n)
    digit_total = 0
    while len(n_str) != 1:
        for digit in n_str:
            digit_total += int(digit)
        n_str = str(digit_total)
    return(n_str)

但它只适用于 2 位数字,它不适用于更高数字的数字,它只是无休止地运行。这段代码可能是一个糟糕的方法,我查看了其他人的答案,我得到了他们的解决方案,但我不明白为什么这不适用于更高的数字。

2 个答案:

答案 0 :(得分:3)

您的程序几乎正确。我看到的唯一挑战是在每次迭代后重置变量 User

digit_total = 0

def digital_root(n): n_str = str(n) while len(n_str) != 1: digit_total = 0 #move this inside the while loop for digit in n_str: digit_total += int(digit) n_str = str(digit_total) return(n_str) print (digital_root(23485)) 的输出是 print (digital_root(23485))

4

如果 2 + 3 + 4 + 8 + 5 = 22 2 + 2 = 4 不在 while 循环中,那么它会不断被添加并且你会得到一个永无止境的循环。

虽然你有很多代码,但你可以在一行中完成。

digit_total = 0

您无需创建太多变量,也无需在跟踪它们时迷失方向。

答案 1 :(得分:0)

亚历克斯, 在这种情况下,运行递归函数总是比 while 循环更好。

试试这个:

def sum_digits(n):
    while len(str(n)) > 1: n = sum(int(i) for i in str(n))
    return n

print (sum_digits(23485))