添加正整数的所有数字

时间:2018-04-03 02:28:26

标签: python python-3.x

我正在尝试添加正整数的所有数字。当我测试数字434时,结果是4而不是11。

这是我所拥有的,我不明白为什么我的代码没有通过该数字的所有数字。如何纠正?

def digit_sum(x):
  n=0
  if x>0:
    #get the end digit of the number,add to n
      n+=x%10
      #remove the end digit of the number
      x=x//10
  return n

4 个答案:

答案 0 :(得分:2)

程序编程的两个主要结构是:

  1. 选择不同的东西一次。 (精选)
  2. 做一次更多的事情。 (迭代)
  3. if语句是一个选择语句。由于您要将所有数字添加到数字中,因此使用if是不合适的。换句话说,使用选择语句只会为您提供所处理的第一个数字的总和(4中的最终数字434)。

    相反,您应该使用像while这样的迭代语句:

    def digit_sum(number):
      sumOfDigits = 0
      while number > 0:
          sumOfDigits += number % 10
          number = number // 10
      return sumOfDigits
    

    您会注意到我使用了更多描述性变量名称。这是一个很好的习惯,因为它会自我记录你的代码。

    您还可以查看更多 Pythonic 方法,例如:

    def digit_sum(number):
        return sum([int(digit) for digit in str(number)])
    

    是否可以将更好视为可以讨论,但这是一种众所周知的编写Python简洁方法。

答案 1 :(得分:1)

使用if语句代替while语句:

def digit_sum(x):
  n=0
  while x>0:
    #get the end digit of the number,add to n
      n+=x%10
      #remove the end digit of the number
      x=x//10
  return n

if只会评估一次,并在一次迭代后返回n的值,同时在循环中运行代码,直到所有数字都加到总和中。

这将给出:

In [2]: digit_sum(10)
Out[2]: 1

In [3]: digit_sum(434)
Out[3]: 11

或者,一个班轮:

In [4]: digit_sum = lambda x: sum(map(int, str(x)))

In [5]: digit_sum(434)
Out[5]: 11

如果不是11,你想再次将这些数字相加得到一个数字,只需递归:

In [6]: def digit_sum(x):
   ...:   n=0
   ...:   while x>0:
   ...:     #get the end digit of the number,add to n
   ...:       n+=x%10
   ...:       #remove the end digit of the number
   ...:       x=x//10
   ...:   return n if n < 10 else digit_sum(n)
   ...: 

In [7]: digit_sum(434)
Out[7]: 2

答案 2 :(得分:1)

虽然这不是一个函数,但对我有帮助:

digits = "12345678901234567890"
digit_sum = sum(map(int, digits))
print("The equation is: ", '+'.join(digits))
print("The sum is:", digit_sum)

(此打印:

The equation is:  1+2+3+4+5+6+7+8+9+0+1+2+3+4+5+6+7+8+9+0
The sum is: 90

答案 3 :(得分:0)

我会将数字转换为字符串,然后解析并对每个数字求和:

def digit_sum(x):
    numList = [int(d) for d in str(x)]
    return sum(numList)