我是编程新手,但最近我一直在尝试算法。我需要使用一个方程来执行计算,该方程使用坐标平面中结构组件中的所有角度作为变量。装配变量,因此我需要这个函数来遍历数据并将装配中每两个点的单独方程组合成用于计算的方程。我感到困惑的部分是如何组合这些功能。如果有这样的事情的话,我想以几乎“类似追加”的方式来做到这一点。
假设我正在查看数据,此时我已经有了函数
a = lambda (x1,x2,x3,x4): (x1*x2)+(x3*x4)
以前是从前两组生成的,现在我想添加一个 eq.从第三组开始
b = lambda (x5,x6): (x5/x6)
def new_lambda(a,b):
return lambda (x1,x2,x3,x4,x5,x6): (x1*x2)+(x3*x4)+(x5/x6)
这是我想要做的一个简单的例子。除了函数创建的基础知识之外,我对任何事情都不太熟悉,所以这可能有点超出我的理解范围。请随意向我推荐一般阅读 Material 。如果需要澄清,我也可以这样做。
最佳答案
我认为问题在于您需要知道每个函数的数量,以便相应地分配“组合”函数的参数。
也许您可以将函数包装在一个类中,如下所示:
class Function:
def __init__ (self, arity, f):
self.arity = arity
self.f = f
def __call__ (self, *args):
return self.f (*args)
def __add__ (self, g):
if not isinstance (g, Function):
raise Exception ('Here be dragons')
def fg (*args):
return self.f (*args [:self.arity] ) + g.f (*args [self.arity:] )
return Function (self.arity + g.arity, fg)
a = Function (4, lambda x1, x2, x3, x4: (x1 * x2) + (x3 * x4) )
b = Function (2, lambda x1, x2: x1 / x2)
print (a (1, 2, 3, 4) )
print (b (10, 20) )
c = a + b
print (c (1, 2, 3, 4, 10, 20) )
关于数量检查的一些话。生成的函数 fg
只有一个参数,即 *x
,其检查的 arity 将结果为 0,因此禁止添加已添加的函数。看看这里:
#Using my original class
a = Function (2, lambda x1, x2: x1 * x2)
b = Function (2, lambda x1, x2: x1 / x2)
c = a + a
print (c (1, 2, 3, 4) ) #prints 14
c = c + b
print (c (1, 2, 3, 4, 5, 6) ) #prints 14.833333333333334
现在,如果我们使用这样的检查(如果您打算使用它的其他用途,请纠正我):
import inspect
class InspectedFunction:
def __init__ (self, f):
self.f = f
def __call__ (self, *args):
return self.f (*args)
def __add__ (self, g):
if not isinstance (g, InspectedFunction):
raise Exception ('Here be dragons')
arity = len (inspect.getargspec (self.f).args)
def fg (*args):
return self.f (*args [:arity] ) + g.f (*args [arity:] )
return InspectedFunction (fg)
a = InspectedFunction (lambda x1, x2: x1 * x2)
b = InspectedFunction (lambda x1, x2: x1 / x2)
c = a + a
print (c (1, 2, 3, 4) ) #prints 14
c = c + b
print (c (1, 2, 3, 4, 5, 6) ) #inspected arity of c is 0
会这样做:
Traceback (most recent call last):
File "nomimporta.py", line 45, in <module>
print (c (1, 2, 3, 4, 5, 6) )
File "nomimporta.py", line 30, in __call__
return self.f (*args)
File "nomimporta.py", line 37, in fg
return self.f (*args [:arity] ) + g.f (*args [arity:] )
File "nomimporta.py", line 37, in fg
return self.f (*args [:arity] ) + g.f (*args [arity:] )
TypeError: <lambda>() takes exactly 2 arguments (0 given)
关于python - 算法中 "combine"函数的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20835559/