我正在尝试创建一个通过迭代运行的“累积”代码。一般来说,组合器接受 2 个参数,例如combiner(x, y) 返回一个函数,例如(x+y) 和项确定每个 a 值的函数,例如term(x) 给出 x^2 意味着 a 的下一个值将是 x^2,而 next 将是确定 a 之后的下一个值的函数,例如x = x+1。
我的代码遇到问题,因为它在某些情况下运行不必要的额外循环(空值必须是退出 while 循环之前循环处理的最后一个值,例如
def accumulate_iter(combiner, null_value, term, a, next, b):
result = term(a)
while a<=b:
a = next(a)
if a<=b:
result = combiner(term(a), result)
else:
result = combiner(null_value, result)
return result
输入的示例如下: accumulate_iter(lambda x,y: xy, 1, lambda x: xx, 1, lambda x: x+1, 5)
输出将为您提供:14400
最佳答案
def accumulate_iter(combiner, term, a, next, b):
result = term(a)
while a <= b:
a = next(a)
if a <= b:
result = combiner(term(a), result)
return result
print(accumulate_iter(lambda x, y: x * y, lambda x: x * x, 1, lambda x: x + 1, 5))
输出:
14400
您还可以完全摆脱额外的循环迭代,这样您就不需要额外的 (x<=y) 测试:
def accumulate_iter(combiner, term, a, next, b):
result = term(a)
a = next(a)
while a <= b:
result = combiner(term(a), result)
a = next(a)
return result
请注意,第二个版本更真实地反射(reflect)了实际情况。循环“组合事物”,这意味着您需要组合两个事物,但每次迭代时只选取一个新事物。因此,在处理第一项并越过它的循环之前有一个特殊情况是很自然的。
关于python - 如何创建通过迭代运行的累积代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54843507/