Below is the problem:
Show that both summation and product are instances of a more general function, called accumulate, with the following signature:
def accumulate(combiner, start, n, term): """Return the result of combining the first n terms in a sequence.""" "*** YOUR CODE HERE ***"
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. Implement accumulate and show how summation and product can both be defined as simple calls to accumulate:
def summation_using_accumulate(n, term): """An implementation of summation using accumulate. >>> summation_using_accumulate(4, square) 30 """ "*** YOUR CODE HERE ***" def product_using_accumulate(n, term): """An implementation of product using accumulate. >>> product_using_accumulate(4, square) 576 """ "*** YOUR CODE HERE ***"
For which, solution is mentioned below:
from operator import add
from operator import mul
def square(x):
""" Retrun x squared"""
return x * x
def accumulate(combiner, start, n, term):
"""Return the result of combining the first n terms in a sequence."""
if n == 0:
return start
else:
start = combiner(term(n), start)
return accumulate(combiner, start, n-1, term)
def summation_using_accumulate(n, term):
"""An implementation of summation using accumulate.
>>> summation_using_accumulate(4, square)
30
"""
assert n >= 0
return accumulate(add, 0, n, term)
def product_using_accumulate(n, term):
"""An implementation of product using accumulate.
>>> product_using_accumulate(4, square)
576
"""
assert n > 0
return accumulate(mul, 1, n, term)
result = summation_using_accumulate(4, square)
print(result)
result = product_using_accumulate(3, square)
print(result)
Please let me know if this program can be improved further using functional paradigm and the DRY principle.