Reduce is often used in combination with map. Google for example has developed a map-reduce framework for querying their databases and this map-reduce pattern is now used in several other projects (e.g. CouchDB, Hadoop, etc).
First, you need to map the input
variables [2, 1, 3, 4, 5]
to something like:
[(1, 2), (1, 1), (1, 3), (1, 4), (1, 5)]
In that case, x[0]
will represent the number of the elements to get the sum x[1]
. Of course, the number of elements is 1
at the beginning for each single element.
The next thing then, is to operate on those tuples:
reduce(
lambda a, b: a if a[1] + b[1] > 8 else (a[0] + b[0], a[1] + b[1]),
map(lambda x: (1, x), input))
This will return (3, 6)
, meaning the partial sum is 6
using 3
elements.
I hope you got the idea behind map-reduce-algorithms.
Regards,
Christoph
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…