首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python求和高阶函数

Python求和高阶函数
EN

Stack Overflow用户
提问于 2019-02-16 21:49:53
回答 1查看 1.3K关注 0票数 1

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

下面是我写的递归代码:

代码语言:javascript
复制
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给出了错误的结果

代码语言:javascript
复制
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提供一个解决方案

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-17 10:23:23

当合并器是可交换的时,你的accumulate_iter工作得很好,但当合并器是非交换的时,它会给出不同的结果。这是因为递归accumulate从后面到前面组合元素,而迭代版本从前面到后面组合元素。

所以我们需要做的是让accumulate_iter从后面组合起来,下面是一个重写的accumulate_iter

代码语言:javascript
复制
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]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54723765

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档