Search code examples
pythonpython-3.xsympysymbolic-math

Cannot substitute values after converting string to expression with Sympify()


I am trying to convert a string into an expression via Sympy like so:

profit = "((MaxSalesCapacity * PctStoreUtilizationRate) * AvgSaleSize) - ((TotalRevenues * AvgCostGoods) + FixedCosts)"
eqn = sympify(profit)

Then I test is to see if it works, this is what I get:

print(eqn)
βˆ’π΄π‘£π‘”πΆπ‘œπ‘ π‘‘πΊπ‘œπ‘œπ‘‘π‘ π‘‡π‘œπ‘‘π‘Žπ‘™π‘…π‘’π‘£π‘’π‘›π‘’π‘’π‘ +π΄π‘£π‘”π‘†π‘Žπ‘™π‘’π‘†π‘–π‘§π‘’π‘€π‘Žπ‘₯π‘†π‘Žπ‘™π‘’π‘ πΆπ‘Žπ‘π‘Žπ‘π‘–π‘‘π‘¦π‘ƒπ‘π‘‘π‘†π‘‘π‘œπ‘Ÿπ‘’π‘ˆπ‘‘π‘–π‘™π‘–π‘§π‘Žπ‘‘π‘–π‘œπ‘›π‘…π‘Žπ‘‘π‘’βˆ’πΉπ‘–π‘₯π‘’π‘‘πΆπ‘œπ‘ π‘‘π‘ 

However, when I try to replace, values, like this: eqn.subs(TotalRevenues, 100), I get this error:

NameError: name 'TotalRevenues' is not defined

What am I doing wrong here? Any advice would be greatly appreciated.


Solution

  • This has nothing to do with any of your API calls. TotalRevenues - the identifier you are passing to eqn.subs was never defined in the Python program. You did define a symbol of that name as part of the expression you passed to sympify, but that does not induce the creation of a Python identifier. You need to put the name of the SymPy symbol in quotes when passing to further API calls. The full code would look like this:

    from sympy import sympify
    
    profit = "((MaxSalesCapacity * PctStoreUtilizationRate) * AvgSaleSize) - ((TotalRevenues * AvgCostGoods) + FixedCosts)"
    eqn = sympify(profit)
    print(eqn)
    seqn = eqn.subs("TotalRevenues", 100)
    print(seqn)
    

    The output wpoiuld look like what I would expect it to look:

    -AvgCostGoods*TotalRevenues + AvgSaleSize*MaxSalesCapacity*PctStoreUtilizationRate - FixedCosts
    -100*AvgCostGoods + AvgSaleSize*MaxSalesCapacity*PctStoreUtilizationRate - FixedCosts
    

    Also, note that the subs() method does not mutate the object for which it called, but instead, returns a new object, with the substitution applied to it. I stored this in the seqn variable.