问题描述
使用sympy
,让我们说一个列表:
xs=[-2,-1,1,2]
我需要获得:
[(x-x_0),(x-x_0)*(x-x_1),(x-x_0)*(x-x_1)*(x-x_2),...(x-x_0)*(x-x_1)*(x-x_2)...*(x-x_n)]
对于我的列表xs
,它将是:
[(x+2),(x+2)*(x+1),(x+2)*(x+1)*(x-1),(x+2)*(x+1)*(x-1)*(x-2)]
我试过了:
terminos = []
def lag_l(xx):
x = Symbol("x")
for x_i in xx:
x__i = ((x-x_i) * prod(t) for t in terminos)
terminos.append((x-x_i))
print terminos[::-1]
所以:
lag_l([-2,-1,1,2])
但这只是打印相同的内容。 我怎么了?
1楼
def product_sequence(xs):
x = Symbol('x')
y = 1
res = []
for item in xs:
y *= x - item
res.append(y)
return res
或者,使用yield
更优雅:
def product_gen(xs):
x = Symbol('x')
y = 1
for item in xs:
y *= x - item
yield y
res = list(product_gen(xs))