T.J.
T.J.

Reputation: 803

Python: Use reduce to alternate addition and multiplication

Using only reduce (so no importing anything), how do I write a one-line function to get the following result? It alternates between adding and multiplying elements in a list.

Everything needs to fit in reduce()

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

((1 + 2) * 3 + 4) * 5 + 6 = 71

Upvotes: 1

Views: 889

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113988

I guess you want something like this:

print(reduce(lambda a, b: a[1] + b[1] if isinstance(a,tuple) 
           else a + b[1] if b[0] % 2 else a * b[1], enumerate(numbers)))

Breakdown:

print( reduce(lambda a, b: a[1] + b[1] if isinstance(a, tuple) 
                           else a + b[1] if b[0] % 2 
                           else a * b[1], 
              enumerate(numbers)
             )
)

Upvotes: 4

cs95
cs95

Reputation: 402523

You can obtain a cleaner solution using something like this:

def myCycle(x, y):
    while True:
        yield from (x, y)  # replace with yield x; yield y for python < 3.3

print (reduce(lambda x, y: (y[0], x[0](x[1], y[1])), 
                  zip(myCycle(int.__add__, int.__mul__), numbers))[-1])
71

myCycle here is a standin for itertools.cycle, which cycles through elements repeatedly.

Upvotes: 3

Related Questions