简体   繁体   English

Python求和高阶函数

[英]Python Summation Higher Order Function

I'm writing an iterative solution for summation, and it seems to give the correct answer. 我正在写一个求和的迭代解决方案,它似乎给出了正确的答案。 But I'm told by my tutor that it's giving the wrong result for non-commutative combine operations . 但是我的老师告诉我,对于non-commutative combine operations ,它给出了错误的结果。 I went to google but I'm still unsure what exactly it means... 我去了谷歌,但我仍然不确定这到底意味着什么...

Here is the recursive code I wrote: 这是我写的递归代码:

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 

This is the iterative version I wrote that gives the wrong results for non-commutative combine operations - Edit: accumulate_iter gives the wrong results when lambda x,y: x- y is used for combiner 这是我写的迭代版本,它non-commutative combine operations提供了错误的结果-编辑:当lambda x,y: x- ylambda x,y: x- y accumulate_iter提供了错误的结果lambda x,y: x- y用于组合器

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

Hoping if someone could provide a solution for this iterative version of accumulate 希望有人可以为accumulate此迭代版本提供解决方案

You accumulate_iter works fine when the combiner is commutative, but it gives different result when the combiner is non-commutative. 当组合器是可交换的时,您accumulate_iter可以正常工作,但是当组合器是不可交换的时,它会给出不同的结果。 That's because the recursive accumulate combine elements from the back to the front, but the iterative version combine them from the front to the back. 那是因为递归从头到尾accumulate组合元素,而迭代版本从头到尾组合它们。

So what we need to do is to make accumulate_iter combine from behind, and following is a rewritten accumulate_iter : 因此,我们需要做的是从后面合并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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM