Question: Let's take a look at how product is an instance of a more general function called accumulate, which we would like to implement: def accumulate

Let's take a look at how product is an instance of a more general function called accumulate, which we would like to implement:
def accumulate(fuse, start, n, term):
"""Return the result of fusing together the first n terms in a sequence
and start. The terms to be fused are term(1), term(2),..., term(n).
The function fuse is a two-argument commutative & associative function.
>>> accumulate(add,0,5, identity) # 0+1+2+3+4+5
15
>>> accumulate(add,11,5, identity) # 11+1+2+3+4+5
26
>>> accumulate(add,11,0, identity) # 11(fuse is never used)
11
>>> accumulate(add,11,3, square) # 11+1^2+2^2+3^2
25
>>> accumulate(mul,2,3, square) # 2*1^2*2^2*3^2
72
>>> # 2+(1^2+1)+(2^2+1)+(3^2+1)
>>> accumulate(lambda x, y: x + y +1,2,3, square)
19
"""
"*** YOUR CODE HERE ***"
accumulate has the following parameters:
fuse: a two-argument function that specifies how the current term is fused with the previously accumulated terms
start: value at which to start the accumulation
n: a non-negative integer indicating the number of terms to fuse
term: a single-argument function; term(i) is the ith term of the sequence
Implement accumulate, which fuses the first n terms of the sequence defined by term with the start value using the fuse function.
For example, the result of accumulate(add,11,3, square) is
add(11, add(square(1), add(square(2), square(3))))=
11+ square(1)+ square(2)+ square(3)=
11+1+4+9=25
Assume that fuse is commutative, fuse(a, b)== fuse(b, a), and associative, fuse(fuse(a, b), c)== fuse(a, fuse(b, c)).
Then, implement summation (from lecture) and product as one-line calls to accumulate.
Important: Both summation_using_accumulate and product_using_accumulate should be implemented with a single line of code starting with return

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!