SymPy: Swap two variables

匿名 (未验证) 提交于 2019-12-03 00:50:01

问题:

In an expression like

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

I'd like to swap a and b to retrieve b + 2*a. I tried

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

but neither works; the result is 3*a in both cases as b, for some reason, gets replaced first.

Any hints?

回答1:

There is a simultaneous argument you can pass to the substitution, which will ensure that all substitutions happen simultaneously and don't interfere with one another 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 keyword simultaneous is True, the subexpressions will not be evaluated until all the substitutions have been made.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!