You can use the in-built reduce
function, which takes a callable, a list and an optional starting element. It calls callable
with a tuple (elem, result)
where element is the ith
element from the list and result
is the result so far.
reduce(lambda item,prod: item * prod, range(1, 5), 1)
Out[2]: 24
So the above would call the lambda function first with (1,1)
, then with (2,1*1)
then (3,2*1)
and finally (4,3*2)
So you'd define add
and mult
and replace your calculate
with the built-in reduce
add = lambda item,cumul_sum: item + cumul_sum
mult = lambda item,product: item * product
reduce(add, range(1,5), 0)
Out[5]: 10
reduce(mult, range(1,5), 1)
Out[6]: 24
http://docs.python.org/2.7/library/functions.html?highlight=reduce#reduce