在python中对连续的第三个数字求和

Rey*_*yer 0 python

我该如何解决这个问题?

该程序应包含该函数的定义sumTri(cutOff).该函数将三个数字添加到总和中.

三个数字是每三个数字:1, 4, 7, 10,.... 1, 4, 7,只要三个数字小于cutOff,该函数就会将连续的三个数字......添加到总和中.该函数返回这些数字的总和.

Igo*_*bin 5

这很简单:

def sumTri(cutOff):
  return sum(range(1,cutOff,3))
Run Code Online (Sandbox Code Playgroud)

或者,当你需要它低级时:

def sumTri(cutOff):
  sum = 0
  tri = 1
  while tri < cutOff:
    sum += tri
    tri += 3
  return sum
Run Code Online (Sandbox Code Playgroud)

我会试着稍微解释两个灵魂.

在第一种情况下,您使用Python的两个"高级"函数,这些函数可以为您完成所有工作:sumrange.的range(a,b,c)函数从产生数字列表ab与台阶c之间.例如:

In [1]: range(1,10,3)
Out[1]: [1, 4, 7]

In [2]: range(1,22,3)
Out[2]: [1, 4, 7, 10, 13, 16, 19]
Run Code Online (Sandbox Code Playgroud)

你必须注意这里range生成数字,直到列表中的数字小于b,而不是小于或等于.正是您的任务所需要的.

sum显然计算并返回,它有作为它的参数列表中的数字的总和:

In [3]: sum([1])
Out[3]: 1

In [4]: sum([1,2])
Out[4]: 3

In [5]: sum([1,2,3])
Out[5]: 6
Run Code Online (Sandbox Code Playgroud)

现在你只需要结合这两个功能:

return sum(range(1,cutOff,3))
Run Code Online (Sandbox Code Playgroud)

第二种解决方案更"低级"和"算法".你在这里没有使用特殊的python函数,并且自己做所有事情.

您使用两个变量来计算总和:

  • sum - 存储金额的变量
  • tri - 具有您逐步添加的当前数字值的变量

当你写下这样的东西:

a = a + 5
Run Code Online (Sandbox Code Playgroud)

这意味着:"现在我想要a等于a之前的加5"或"增加a5".你可以写得更短:

a += 5 
Run Code Online (Sandbox Code Playgroud)

这两种形式是等价的.

但你不需要简单地添加一些东西.你需要做很多次,直到发生了什么事.在python中你可以使用while:

while someting-is-true:
  do-something
Run Code Online (Sandbox Code Playgroud)

每次while检查something-is-true条件,当它为True时,它会生成while(缩进)的命令,即do-something.

现在您知道编写解决方案所需的一切:

def sumTri(cutOff):
  sum = 0                      # we start the sum from 0
  tri = 1                      # and the first number to add is 1
  while tri < cutOff:          # next number to add < cutOff?
    sum += tri                 # than add it to sum
    tri += 3                   # and increase the number by 3
  return sum                   # now you have the result, return it
Run Code Online (Sandbox Code Playgroud)

这就是完成工作的功能.现在您可以使用该功能.你是怎么做到的?

def sumTri(cutOff):
  ...

# anywhere in you program:
# presuming a is the cutOff
print sumTri(a)
Run Code Online (Sandbox Code Playgroud)

当你想运行该函数并使用它的结果时,你只需编写function_name(args).

  • 可能是家庭作业 - 也许解释你的工作? (2认同)
  • 对于1000000的截止,我的答案是快40000倍 (2认同)