簡體   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