For the below query, 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 ***"
Below is the solution:
from operator import mul, add
def accumulate(combiner, start, n, f):
"""Return the result of combining the first n terms in a sequence."""
total = start #Result of summation gets stored here
i = 1 #Initial value of sequence
while i <= n:
total = combiner(total, f(i))
i = i + 1
return total
def summation_using_accumulate(n, f):
"""An implementation of summation using accumulate.
>>> summation_using_accumulate(4, square)
30
"""
return accumulate(add, 0, n, f)
def product_using_accumulate(n, f):
"""An implementation of product using accumulate.
>>> product_using_accumulate(4, square)
576
"""
return accumulate(mul, 1, n, f)
def square(x):
return mul(x, x)
print("product_using_accumulate: ",product_using_accumulate(4, square))
print("summation_using_accumulate: ",summation_using_accumulate(4, square))
print(accumulate(add, 0, 4, square))
print(accumulate(mul, 1, 4, square))
I have tested this code and looks good to me.
My questions:
Does the solution look incorrect in any aspect?
Any feedback on naming conventions?
Any feedback on coding style?
..._using_accumulate
functions actually useaccumulate
! Your calls at the end should be inside those functions. – jonrsharpe Jul 11 '14 at 11:26neither of your ..._using_accumulate functions actually use accumulate!
, i still did not understand, where is this point asked in the query? Please help me!! – overexchange Jul 11 '14 at 12:45accumulate
. And in terms of "feedback on Coding style" - see the style guide. – jonrsharpe Jul 11 '14 at 12:46..._using_accumulate
?! The purpose is not just to minimise the code (Python hassum
andreduce
built right in, so why bother with any of this?), it's to understand the processes involved. – jonrsharpe Jul 11 '14 at 13:00