質問

Using sympy, let's say a list:

xs=[-2,-1,1,2]

And I need to get:

[(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)]

For my list xs, that would be:

[(x+2),(x+2)*(x+1),(x+2)*(x+1)*(x-1),(x+2)*(x+1)*(x-1)*(x-2)]

I've tried:

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]

And so:

lag_l([-2,-1,1,2])

But that's only printing the same back. What have I got wrong?

役に立ちましたか?

解決

def product_sequence(xs):
  x = Symbol('x')
  y = 1
  res = []
  for item in xs:
     y *= x - item
     res.append(y) 
  return res

Or, more elegant using yield:

def product_gen(xs):
  x = Symbol('x')
  y = 1
  for item in xs:
     y *= x - item
     yield y

res = list(product_gen(xs))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top