在python中生成多项式lambda表达式

时间:2017-05-28 10:02:41

标签: python lambda

如何使以下代码通用,而不总结不同 例:

def poly(n):
    if n == 1: return lambda x,a,b: x*a+b
    if n == 2: return lambda x,a,b,c: x*x*a+x*b+c
    if n == 3: return lambda x,a,b,c,d: x*x*x*a+x*x*b+x*c+d

2 个答案:

答案 0 :(得分:3)

你可以传递系数列表并手动评估多项式":

def fn1(coefs):
    def g(x):
        ret = coefs[0]
        for i in range(1, len(coefs)):
            ret *= x
            ret += coefs[i]
        return ret

    return g

def fn2(coefs, x):
    ret = coefs[0]
    for i in range(1, len(coefs)):
        ret *= x
        ret += coefs[i]
    return ret


x = 2.5
g = fn1([2, 3, 4])
assert( g(x) == 2*x*x + 3*x + 4 )

assert( fn2([2, 3, 4], x) == 2*x*x + 3*x + 4 )

答案 1 :(得分:2)

与ewcz的答案类似,但是递归(并使用* args以避免需要传递列表/元组):

def poly(n):
    def poly_h(n,x,*args):
        if n == 0:
            return args[0]
        return args[0] * x ** n + poly_h(n-1,x,*args[1:])
    nn = n
    return lambda *args: poly_h(nn,*args)

third = poly(3)
print third(2,1,2,3,4) == 2**3+2**3+2*3+4
print third(3,1,2,3,4) == 3**3+2*3**2+3*3+4
second = poly(2)
print second(1,2,3,4) == 2 + 3 + 4
print third(2,1,2,3,4) == 2**3+2**3+2*3+4