Search code examples
pythonlistreducepython-itertools

Multiplying paired elements in python using reduce


For a list like:

a = [1,2,3,4,5,6] 

I want to use the code below to multiply paired elements like this:

(a[0] + a[1]) * (a[2] + a[3]) * (a[4] + a[5])

I've tried using something like:

reduce((lambda x, y: (x+y)), numbers) 

and:

reduce((lambda x, y: (x+y)*(x+y)), numbers) 

But I don't know how to make it work over the entire list. Any help would be greatly appreciated.

The entire solution must fit withing the reduce and I cannot import any other modules.


Solution

  • It can be done in two steps:

    1. sum consecutive items in the list: [sum(a[i:i+2]) for i in range(0, len(a), 2)]
    2. apply the reduction: reduce(lambda x, y: x * y, new_list)

    Compose them together:

    reduce(lambda x, y: x * y, [sum(a[i:i+2]) for i in range(0, len(a), 2)])