Ask Your Question
1

Substitution of a list of variables

asked 2013-10-13 12:44:43 -0500

updated 2015-01-14 07:15:59 -0500

FrédéricC gravatar image

I wish substituting a list of variables, without having to substitute them 1 by 1.
Here is an example with an attempt which doesn't work :

sage: V=[var('x_%d' % i) for i in range(10)]; V
[x_0, x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9]
sage: S=[sum(V),prod(V)]; S
[x_0 + x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8 + x_9,
x_0*x_1*x_2*x_3*x_4*x_5*x_6*x_7*x_8*x_9]
sage: for i in range(10):
....:     S.subs(V[i]=i)
....:     
  File "<ipython-input-99-7670392e3358>", line 2
SyntaxError: keyword can't be an expression

How can we do this ?

edit retag flag offensive close merge delete

1 answer

Sort by » oldest newest most voted
1

answered 2013-10-13 13:07:22 -0500

calc314 gravatar image

updated 2013-10-13 13:10:50 -0500

Here is a possible solution using a dictionary to do all of the substitutions at once.

var('x1,x2,x3')
V=[x1,x2,x3]
s=sum(V)
V_vals=[2,3,4]
s.subs({V[i]:V_vals[i] for i in range(0,3)})

For your example, couple this with a map command.

V=[var('x_%d' % i) for i in range(10)]
S=[sum(V),prod(V)]
map(lambda q: q.subs({V[i]:i for i in range(0,len(V))}),S)
edit flag offensive delete link more

Comments

Thank you!

Sébastien Palcoux gravatar imageSébastien Palcoux ( 2013-10-13 21:35:21 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-10-13 12:44:43 -0500

Seen: 583 times

Last updated: Oct 13 '13