Python求和高阶函数

用户名

我正在写一个求和的迭代解决方案,它似乎给出了正确的答案。但是我的老师告诉我,它给带来了错误的结果non-commutative combine operations我去了谷歌,但我仍然不确定这到底意味着什么...  

这是我写的递归代码:

def sum(term, a, next, b):
    # First recursive version
    if a > b:
        return 0
    else:
        return term(a) + sum(term, next(a), next, b)

def accumulate(combiner, base, term, a, next, b):
    # Improved version
    if a > b:
        return base
    else:
        return combiner(term(a), accumulate(combiner, base, term, next(a), next, b))

print(sum(lambda x: x, 1, lambda x: x, 5))
print(accumulate(lambda x,y: x+y, 0, lambda x: x, 1, lambda x: x, 5))
# Both solution equate to - 1 + 2 + 3 + 4 + 5 

这是我编写的迭代版本,给出了错误的结果non-commutative combine operations-编辑:当lambda x,y: x- y用于合并器时,accumulate_iter给出错误的结果

def accumulate_iter(combiner, null_value, term, a, next, b):
    while a <= b:
        null_value = combiner(term(a), null_value)
        a = next(a)
    return null_value

希望有人可以为该版本的迭代版本提供解决方案 accumulate

不知道

accumulate_iter当组合器是可交换的时,可以很好地工作,但是当组合器是不可交换的时,它会提供不同的结果。这是因为递归从头到尾accumulate组合了元素,而迭代版本则从头到尾组合了元素。

因此,我们需要做的是accumulate_iter从后面进行合并,然后重写accumulate_iter

def accumulate_iter(a, b, base, combiner, next, term):
    # we want to combine from behind, 
    # but it's hard to do that since we are iterate from ahead
    # here we first go through the process, 
    # and store the elements encounted into a list
    l = []
    while a <= b:
        l.append(term(a))
        a = next(a)
    l.append(base)
    print(l)

    # now we can combine from behind!
    while len(l)>1:
        l[-2] = combiner(l[-2], l[-1])
        l.pop()
    return l[0]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章