SymPy: sharing two variables

In a type expression

import sympy a = sympy.Symbol('a') b = sympy.Symbol('b') x = a + 2*b 

I would like to exchange a and b for a choice of b + 2*a . I tried

 y = x.subs([(a, b), (b, a)]) y = x.subs({a: b, b: a}) 

but does not work; the result of 3*a in both cases as b for some reason replaced first.

Any clues?

+5
source share
1 answer

There is a simultaneous argument that you can pass to substitution, which ensures that all replacements will be performed at the same time and will not interfere with each other, as they are doing now.

 y = x.subs({a:b, b:a}, simultaneous=True) 

Outputs :

 2*a + b 

From the docs for subs :

If the simultaneous keyword is True , the subexpressions will not be evaluated until all the substitutions are done.

+4
source

All Articles