Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive substitution in sympy

Tags:

I have a sympy expression with multiple variables that need to be substituted out. The problem is that the some of the expressions to be substituted in also contain instances of variables that need to be substituted out.

from sympy import *
from sympy.abs import a,b, x,y

expr = a + b
replace = [[a, x+y], [b, 2*a]]

expr.subs(replace) # 2*a + x + y, I want 3*x + 3*y

If the replacement list is in the right order, it will apply each substitution sequentially, though in my real application I don't know what order would be appropriate:

expr.subs(reversed(replace)) # 3*x + 3*y

I can force the substitution by applying the substitution n times to either expr or replace, but that seems computationally wasteful:

result = expr
for _ in replace:
    # Applying n times
    result = result.subs(replace)

I was hoping for a recursive option to subs, but that doesn't seem to exist. Any better options?