Can I add an iterator to the reduce function?

Viewed 317

Suppose I have the following list: A = [1,2,3,4], By using the reduce function, to find the product of the elements, I could do

prodA = reduce(lambda x,y: x*y, A)

However, if I have another list B=[9,8,7,6], is it still possible for me to use the reduce function to execute the following action? (from top to the bottom indicate the steps)

9
(9+1)* 2
((9+1) *2)+8
(((9+1) *2)+8)*3
((((9+1) *2)+8)*3)+7
(((((9+1) *2)+8)*3)+7)*4
((((((9+1) *2)+8)*3)+7)*4)+6

I'm not pretty sure if I could add something like an iterator for the list B to the reduce function. How I can do that? Thanks a lot!

2 Answers

This looks like a job for zip. Specifically, we're going to zip the two lists together, and then we'll express our reduction function as a function that takes tuples instead of simple integers.

Zipping our lists together gives us

>>> list(zip(A, B))
[(1, 9), (2, 8), (3, 7), (4, 6)]

And your function, at each step, multiplies by an element of A and then adds an element of B. So, starting with 1 (which is a sensible default since the first thing we do is multiply, so the 1 will be the identity for that first operation), multiply by the first element of the tuple and add the second.

reduce(lambda x, y: x * y[0] + y[1], zip(A, B), 1)

And, with your inputs, we get 370, which is equal to

((((9+1)*2)+8)*3+7)*4+6

You can do it using zip as the input and 1 as the initial value:

from functools import reduce

A = [1,2,3,4]
B = [9,8,7,6]

r = reduce(lambda r,ab: r*ab[0]+ab[1],zip(A,B),1)
print(r) # 370
Related