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.
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.