Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

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 == 2:
    f = lambda u1, u2 : (u1*u2)*(u1**2+u2**2)
if dim == 3:
    f = lambda u1, u2, u3 : (u1*u2*u3)*(u1**2+u2**2+u3**2)
if dim == 4:
    f = lambda u1, u2, u3, u4 : (u1*u2*u3*u4)*(u1**2+u2**2+u3**2+u4**2)

How can the lambda function be written so that it can expand itself in the call lambda u1, u2, u3, u4, ... as well as the function body itself, based on number of inputs sent to it, similar to how a defined function can be declared as def f(*args) where *args is an arbitrary number of input arguments?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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**2 for 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**2 for u in us))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...