Timocaillou
Timocaillou

Reputation: 3

How to substitute an Integer by a sum in an expression

Hi I edited my question because I found out that my problem was larger: I can't use the subs function: This:

from sympy import *
x, y, z = symbols("x y z")

expr = x
expr.subs(x, y)
print(expr)

Gives me an "x". May this be because I'm using sympy with anaconda?

Question previous to the editing:

I'm new at sympy, here's my problem: I would like to replace the value 5 by a sum (3+2) and can't manage it with a .subs, i tried it this way:

from sympy import *
    
def change(expr):
    '''
    if it's a leaf substitute 5 by 3+2
    '''
    if len(expr.args)==1:
        expr.subs(UnevaluatedExpr(5), UnevaluatedExpr(3) + UnevaluatedExpr(2))
        print(expr)
    for arg in expr.args: 
        change(arg)
    
expr = UnevaluatedExpr(5)*UnevaluatedExpr(10)-UnevaluatedExpr(5)**UnevaluatedExpr(2)
#i.e. 5*10-5^2
change(expr)          #should substitue 5s by (2+3)

But instead it does not change anything :/ If you have any ideas about what I'm doing wrong I would be very please, thanks in advance ! Edit: I had an error in the subs function but it still doesn't work now it's fixed

Upvotes: 0

Views: 76

Answers (2)

smichr
smichr

Reputation: 19057

Since expressions are immutable, using subs on an expression does nothing to the original expression, it only creates a new (possibly different) expression. So the observation that expr is still x after your did expr.subs(x,y) is consistent with that. If you had printed expr.subs(x,y) you would have seen y.

Also, since your change function does not return the new expression when you check the value of expr it is unchanged.

If you want to write your own function you can ask for help on that. If you want to replace an Integer with a sum you can use the subs method itself:

>>> expr = UnevaluatedExpr(5)*UnevaluatedExpr(10)-UnevaluatedExpr(5)**UnevaluatedExpr(2)
>>> expr.subs(5, UnevaluatedExpr(2)+3)
(3 + 2)*10 - (3 + 2)**2
>>> expr  # unchanged unless you do expr = expr.subs(5, UnevaluatedExpr(2)+3)
5*10 - 5**2

Upvotes: 1

Davide_sd
Davide_sd

Reputation: 13170

I think you got the arguments of subs in the wrong order. Here is how you do that:

expr.subs(UnevaluatedExpr(5), UnevaluatedExpr(3) + UnevaluatedExpr(2))
# out: (2 + 3)*10 - (2 + 3)**2

Upvotes: 1

Related Questions