Ask Your Question
3

Substitution of a list of variables

asked 2013-10-13 19:44:43 +0100

updated 2015-01-14 14:15:59 +0100

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
2

answered 2013-10-13 20:07:22 +0100

calc314 gravatar image

updated 2013-10-13 20:10:50 +0100

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-14 04:35:21 +0100 )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

1 follower

Stats

Asked: 2013-10-13 19:44:43 +0100

Seen: 2,449 times

Last updated: Oct 13 '13