繁体   English   中英

Python求和高阶函数

[英]Python Summation Higher Order Function

我正在写一个求和的迭代解决方案,它似乎给出了正确的答案。 但是我的老师告诉我,对于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- 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

希望有人可以为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]

暂无
暂无

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

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