对于下面的查询,请显示和积都是一个更一般函数的实例,称为累计,并具有以下签名: def累计(组合器、开始、n、术语):“返回序列中第一个n项组合的结果。”“*这里的代码以相同的参数项作为参数,n作为求和和积,连同一个组合器函数(由两个参数组成),该函数指定如何将当前项与前面项的累积组合,以及指定用于开始积累的基值的起始值。实现累积,并说明如何将求和和积定义为简单的累积调用: def summation_using_accumulate(n,term):“”是使用累加的求和实现。>>> summation_using_accumulate(4,square) 30“”*您在这里的代码*“def product_using_accumulate(n,term):”是使用累积的产品的实现。>>> product_using_accumulate(4,square) 576“”*您的代码在这里*“
以下是解决办法:
from operator import mul, add
def accumulate(combiner, start, n, f):
"""Return the result of combining the first n terms in a sequence."""
total = start #Result of summation gets stored here
i = 1 #Initial value of sequence
while i <= n:
total = combiner(total, f(i))
i = i + 1
return total
def summation_using_accumulate(n, f):
"""An implementation of summation using accumulate.
>>> summation_using_accumulate(4, square)
30
"""
return accumulate(add, 0, n, f)
def product_using_accumulate(n, f):
"""An implementation of product using accumulate.
>>> product_using_accumulate(4, square)
576
"""
return accumulate(mul, 1, n, f)
def square(x):
return mul(x, x)
print("product_using_accumulate: ",product_using_accumulate(4, square))
print("summation_using_accumulate: ",summation_using_accumulate(4, square))
print(accumulate(add, 0, 4, square))
print(accumulate(mul, 1, 4, square))我已经测试过这段代码,看上去不错。
我的问题:
发布于 2014-07-11 13:12:41
以下是我认为你们被引导到的实施方案:
##from functools import reduce # if Python 3.x
from operator import add, mul
def accumulate(combiner, start, n, f):
"""Return the result of combining the first n terms in a sequence."""
## return reduce(combiner, (f(i+1) for i in range(n)), start) # <- built-in version
total = start
for i in range(n):
total = combiner(total, f(i+1))
return total
def summation_using_accumulate(n, f):
"""An implementation of summation using accumulate.
>>> summation_using_accumulate(4, square)
30
"""
return accumulate(add, 0, n, f)
def product_using_accumulate(n, f):
"""An implementation of product using accumulate.
>>> product_using_accumulate(4, square)
576
"""
return accumulate(mul, 1, n, f)
def square(x):
return mul(x, x)所以你才能
说明如何将求和和积定义为简单的累积调用。
也就是说,只需这样做,就能取得所需的结果:
>>> product_using_accumulate(4, square)
576
>>> summation_using_accumulate(4, square)
30另外,请注意for和range的使用,这两种方法在while循环中手动递增值更容易,也更不容易出错。
所以你的具体问题的答案是:
accumulate,product_using_accumulate和summation_using_accumulate都错了,但你现在已经修好了;Currentterm (应该是current_term -根据样式指南,变量名是lowercase_with_underscores);以及return accumulate(add,0,n,f)应该是return accumulate(add, 0, n, f)。发布于 2014-07-11 11:28:29
start“指定要使用什么值来开始积累”,但是在您的实现中,start是序列中贡献积累的第一个项的索引。这两个测试用例都有start=1和f(1)=1,因此它们无法检测您的错误。summation_using_accumulate和product_using_accumulate的实现实际上并不使用accumulate!https://codereview.stackexchange.com/questions/56744
复制相似问题