[Tutor] Project Euler #8
Alan Gauld
alan.gauld at btinternet.com
Fri May 31 23:42:13 CEST 2013
On 31/05/13 21:49, Nick Shemonsky wrote:
> I did stumble upon using reduce ...but I didn't really
> understand what it was doing
>> def product(intlist):
>> return reduce(operator.mul, intlist)
I explain reduce thusly in my Functional Programming topic:
---------------------
The reduce function is a little less obvious in its intent. This
function reduces a list to a single value by combining elements via a
supplied function. For example we could sum the values of a list and
return the total like this:
def add(i,j): return i+j
print reduce(add, numbers)
As before we could do this more conventionally like this:
res = 0
for i in range(len(numbers)): # use indexing
res = res + numbers[i]
print res
While that produces the same result in this case, it is not always so
straightforward. What reduce actually does is call the supplied function
passing the first two members of the sequence and replaces them with the
result. In other words a more accurate representation of reduce is like
this:
def reduce(numbers):
L = numbers[:] # make a copy of original
while len(L) >= 2:
i,j = L[0],L[1] # use tuple assignment
L = [i+j] + L[2:]
return L[0]
----------------------
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list