Python:多个参数/不带/functools的函数的组合



正在编写一个看似简单的函数,用于查找事物的累积。它非常抽象,其签名是:

def accumulate(combiner, start, n, term):
"""Return the result of combining the first n terms in a sequence."""
"*** YOUR CODE HERE ***"

关于这个问题的更多信息:

"Accumulate采用相同的自变量项作为自变量,n作为求和和和乘积,再加上一个组合器函数(由两个自变量组成),该函数指定如何将当前项与前面项的累积相组合,以及一个起始值,该起始值指定使用什么基值来开始累积。"——摘自加州大学伯克利分校CS61A 2013年秋季,John DeNero

"组合器"指的是从"开始"到"n"的术语的累积方式(可以是add、sub、mul等)。组合器最多需要2个参数。

"术语"是指应用于以"start"开头、以"n"结尾的每个术语的函数。这可能意味着取每个术语的平方sqrt,n%//2。

我想在不必使用functools.reduce.的情况下解决这个问题

我知道我必须做一个函数组合的循环,但这是让我困惑的部分。然后,我必须让每个函数接受两个参数:旧的累积和当前的术语。

我已经做了两天了,我把自己弄糊涂了,所以我的代码一团糟。有什么建议吗?

def accumulate(combiner, start, n, term):
"""Return the result of combining the first n terms in a sequence."""
now=0
while start+now+1<=n:
def combiner(x,y):
old=combiner(start+now,start+now+1)
old=combiner(old,start)
now+=1
return old

"start+now+1"指的是这样一个事实,即在我至少有n项之前,我不能开始对项(n)执行组合器函数。但后来我变得困惑了,因为我必须在存储旧和并更新它的同时不断组合最后2个值。

您不需要在函数中使用函数。只需这样做:

def accumulate(combiner, start, n, term):
"""Return the result of combining the first n terms in a sequence."""
total = term(start)
current = start
while current < n:
total = combiner(total, term(current))
current += 1
return total

最新更新