【问题标题】:Don't understand why code for digit sum isn't working不明白为什么数字总和的代码不起作用
【发布时间】:2021-01-11 23:45:33
【问题描述】:

我尝试解决 codewars Sum of Digits/Digital Root 问题,您必须:

给定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 位数字,它不适用于更高位的数字,它只是无休止地运行。这段代码可能是一种不好的方法,我查看了其他人的答案,我得到了他们的解决方案,但我只是不明白为什么这不适用于更高的数字。

【问题讨论】:

  • 是否需要在循环顶部将digital_total重置为0?
  • @xdhmoore 也是这么想的,他需要在分配n_str 后重置digit_total 否则他只是再次将之前的结果加到总和中

标签: python


【解决方案1】:

您的程序几乎是正确的。我看到的唯一挑战是在每次迭代后重置变量 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

如果 digit_total = 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))

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

【讨论】:

  • 我正要过来看看有没有人回复时才意识到这一点,非常感谢!!
【解决方案2】:

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

试试这个:

def digital_root(n):
    n=sum([int(i) for i in str(n)])

    if len(str(n))==1:
        print(n)     
    else:
        digital_root(n)

【讨论】:

    猜你喜欢
    • 2010-12-14
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    相关资源
    最近更新 更多