使用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])
但那只是打印相同的背面。我有什么问题?
答案 0 :(得分: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))