Вопрос

Working on writing a deceptively simple function that finds the accumulation of things. It is quite abstract, and its signature is this:

def accumulate(combiner, start, n, term):
    """Return the result of combining the first n terms in a sequence."""
    "*** YOUR CODE HERE ***"

More about this question:

"Accumulate takes as arguments the same arguments term and n as summation and product, together with a combiner function (of two arguments) that specifies how the current term is to be combined with the accumulation of the preceding terms and a start value that specifies what base value to use to start the accumulation." --from UC Berkeley CS61A Fall 2013, John DeNero

"Combiner" refers to the way that the terms from "start" to "n" will be accumulated (could be add, sub, mul, etc.). Combiner takes 2 arguments max.

"Term" refers to the function that is applied to each term beginning with "start" and ending with "n." This could mean taking the square, sqrt, n%//2, of each term.

I want to approach this problem without having to use functools.reduce.

I know I have to make a loop of function compositions, but this is the part that confuses me. And then, I have to have each function take two arguments: the old accumulation and the current term.

I have worked on this for 2 days, and have confused my self a bunch, so my code is messed up. Any suggestions?

def accumulate(combiner, start, n, term):
    """Return the result of combining the first n terms in a sequence."""
    now=0
    while start+now+1<=n:
        def combiner(x,y):
                old=combiner(start+now,start+now+1)
                old=combiner(old,start)
                now+=1
    return old

The "start+now+1" refers to the fact that I can't start performing the combiner function on term(n) until I have at least term of n. But then I become confused because I have to keep combining the last 2 values while storing the old sum and updating it.

Это было полезно?

Решение

You don't need to use a function within a function. Just do something like this:

def accumulate(combiner, start, n, term):
    """Return the result of combining the first n terms in a sequence."""
    total = term(start)
    current = start
    while current < n:
        total = combiner(total, term(current))
        current += 1
    return total
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top