Skip to content Skip to sidebar Skip to footer

Multivariate Lambda Function In Python That Scales With Number Of Input Variables Received

The following toy function ordinarily takes two input variables: f = lambda u1, u2 : (u1*u2)*(u1**2+u2**2) but can scale beyond the bivariate case to higher dimensions: if dim ==

Solution 1:

The lambda syntax supports the same parameter list syntax as the def syntax, including variadic positional and keyword argument.

f = lambda *us: math.prod(us) * sum(u**2for u in us)

If the *us are not invariant when multiplied by 1 or added to 0, the * and + operations can be applied across elements via reduce:

from functools import reduce
import operator

f = lambda *us: reduce(operator.mul, us) * reduce(operator.add, (u**2for u in us))

Post a Comment for "Multivariate Lambda Function In Python That Scales With Number Of Input Variables Received"