简体   繁体   中英

Parsing a dictionary of strings that refer to each other into SymPy expressions

I have a python dictionary like this:

A = {'a':'x**2', 'b':'a*x', 'c':'b'}

Here x is a sympy variable. Now I want to get the derivatives like this:

da/dx = 2*x, db/dx = 3*x**2, dc/dx = 3*x**2

So a , b and c has to be considered as the LHS of three different expressions and x is the only sympy variable.

I tried using sympify , but that only converts RHS from a string to expression. For the differentiation I want to use sy.diff . How can I do this?

This is a tricky dictionary, which has to be read several times to find out what means what. So I'll use a "repeated subs" helper:

def repeated_subs(expr, dict):
    while True:
        new_expr = expr.subs(dict)
        if new_expr == expr:
            return expr
        else:
            expr = new_expr

Now the rest is easy:

x = symbols('x')    
B = {S(key): S(A[key], locals={'x': x}) for key in A}   # S is short for sympify
for key in B:
    pprint(Eq(Derivative(key, x), repeated_subs(key, B).diff(x)))

This prints

d          
──(a) = 2⋅x
dx         
d          2
──(b) = 3⋅x 
dx          
d          2
──(c) = 3⋅x 
dx     

The part locals={'x': x} is optional here, but in general it is needed to make sure that the string character "x" gets mapped to the symbol x that was already created, instead of something new.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM