Jos Vrancken
Jos Vrancken

Reputation: 51

generating polynomial lambda expressions in python

How to make the following code generic, without summing up the different cases:

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

Upvotes: 1

Views: 386

Answers (2)

Foon
Foon

Reputation: 6468

Similar to ewcz's answer, but recursive (and uses *args to avoid needing to pass a list/tuple):

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

Upvotes: 2

ewcz
ewcz

Reputation: 13097

you could pass a list of coefficients and evaluate the polynomial "manually":

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 )

Upvotes: 3

Related Questions