defaccumulate(merger, start, n, term): """Return the result of merging the first n terms in a sequence and start. The terms to be merged are term(1), term(2), ..., term(n). merger is a two-argument commutative 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 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 >>> # ((2 * 1^2 * 2) * 2^2 * 2) * 3^2 * 2 >>> accumulate(lambda x, y: 2 * x * y, 2, 3, square) 576 >>> accumulate(lambda x, y: (x + y) % 17, 19, 20, square) 16 """ "*** YOUR CODE HERE ***" sum = start for i inrange(n): sum = merger(sum,term(i+1)) returnsum
accumulate has the following parameters:
term and n: the same parameters as in product
merger: a two-argument function that specifies how the current term is merged with the previously accumulated terms.
start: value at which to start the accumulation.
For example, the result of accumulate(add, 11, 3, square) is
1
11 + square(1) + square(2) + square(3) = 25
Note: You may assume that merger is commutative. That is, merger(a, b) == merger(b, a) for all a and b. However, you may not assume merger is chosen from a fixed function set and hard-code the solution.
After implementing accumulate, show how summation and product can both be defined as function calls to accumulate.
Important: You should have a single line of code (which should be a return statement) in each of your implementations for summation_using_accumulate and product_using_accumulate, which the syntax check will check for.
defsummation_using_accumulate(n, term): """Returns the sum: term(0) + ... + term(n), using accumulate. >>> summation_using_accumulate(5, square) 55 >>> summation_using_accumulate(5, triple) 45 >>> # You aren't expected to understand the code of this test. >>> # Check that the bodies of the functions are just return statements. >>> # If this errors, make sure you have removed the "***YOUR CODE HERE***". >>> import inspect, ast >>> [type(x).__name__ for x in ast.parse(inspect.getsource(summation_using_accumulate)).body[0].body] ['Expr', 'Return'] """ return accumulate(add, term(0), n, term)
defproduct_using_accumulate(n, term): """Returns the product: term(1) * ... * term(n), using accumulate. >>> product_using_accumulate(4, square) 576 >>> product_using_accumulate(6, triple) 524880 >>> # You aren't expected to understand the code of this test. >>> # Check that the bodies of the functions are just return statements. >>> # If this errors, make sure you have removed the "***YOUR CODE HERE***". >>> import inspect, ast >>> [type(x).__name__ for x in ast.parse(inspect.getsource(product_using_accumulate)).body[0].body] ['Expr', 'Return'] """ return accumulate(mul, 1, n, term)