我该如何解决这个问题?
程序应该包含函数sumTri(cutOff)的定义。该函数将三个数字相加到总和中。
三个数字是每三个数字:1, 4, 7, 10, ....该函数将连续的三个数字1, 4, 7,相加...只要Tri数小于cutOff,就将其转化为总和。该函数返回这些数字的总和。
发布于 2012-06-18 12:07:25
这很简单:
def sumTri(cutOff):
return sum(range(1,cutOff,3))或者,当你需要它的时候:
def sumTri(cutOff):
sum = 0
tri = 1
while tri < cutOff:
sum += tri
tri += 3
return sum我会试着解释一下这两种想法。
在第一种情况下,您使用了Python的两个“高级”函数:sum和range。range(a,b,c)函数生成一个从a到b的数字列表,其间的步长为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]这里必须注意,直到列表中的数字小于b,而不是小于或等于,range才会生成数字。这正是你完成任务所需要的。
显然,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现在您只需要将这两个函数组合在一起:
return sum(range(1,cutOff,3))第二种解决方案更“低级”和“算法”。您在这里没有使用特殊的python函数,所有的工作都由您自己完成。
您可以使用两个变量来计算和:
sum --存储数字的变量--使用sumtri的当前值逐步添加的变量
当您编写类似以下内容的代码时:
a = a + 5这意味着:“现在我希望a等于之前的a加5”或“将a增加5”。你可以把它写得更短:
a += 5 这两种形式是等价的。
但是你不需要简单的添加一些东西。你需要做很多次,直到有什么事情发生。在python中,您可以使用while来完成
while someting-is-true:
do-something每次while检查something-is-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这就是这项工作的功能。现在你可以使用这个函数了。你是怎么做到的?
def sumTri(cutOff):
...
# anywhere in you program:
# presuming a is the cutOff
print sumTri(a)当您想运行函数并使用其结果时,只需编写function_name(args)即可。
发布于 2012-06-18 12:21:04
https://stackoverflow.com/questions/11076782
复制相似问题