Reduce() with a regular function

100 Views Asked by At

I want to calculate the product sum of two lists using reduce() and a regular function.

The regular function to return the product is defined as:

    def func(maturity, weight):
        return maturity * weight

and the reduct function is like:

reduce(func, zip(terms, weights))

An error

"TypeError: can't multiply sequence by non-int of type 'tuple'" 

then appears. Is there any way to pass the regular function instead of lambda to calculate the product sum of the two lists?

2

There are 2 best solutions below

1
On BEST ANSWER

I think you're mis-understanding the use of reduce. What it does is apply an operation repeatedly on a vector to produce a scalar as the end result. What you want to do is apply the same function on separate elements which are not related. For that purpose, you need map:

out = map(func, terms, weights)

As Jon Clements noted, if your function is as simple as element-wise multiplication, you might consider using operator.mul instead:

import operator
out = map(operator.mul, terms, weights)
2
On

Error is because you are multiplying tuples, Both arguments in func are tuples which looks like this

('A', 1), ('B', 2)

If you take elements on index 1 it will work.

def func(maturity, weight):
    return maturity[1] * weight[1]


terms = ['A', 'B', 'C']
weights = [1, 2]

reduce(func, zip(terms, weights))

snippet