0

I new with Python and much more with Sympy, I'm trying to solve an equation; the user introduces the equation and the value of 'x'. Example: eq: x**2+x*3+1, x = 4, so the 4 should be replaced on the 'x' of the equation and calculate the result.

This is what I have been trying:

import sympy
from sympy.solvers import solve
from sympy.core.function import Derivative
from sympy.core.relational import Eq
from sympy.core.symbol import Symbol

x = Symbol('x')

info = input("Introduce the equation and the value of /'x' \nEg: x**3+x**2+1 9\n")

infoList = info.split()

equation = infoList[0]
x_value = infoList[1]

expr = equation
eqResult = expr.subs(x, x_value)

print(eqResult)

The error is that the expr, which is an str object, has no attribute subs. Any help is appreciated.

UPDATE

The function eval() works fine, but is there a solution less risky? I have been doing other stuff and tried to calculate the Derivative of the function:

x = Symbol('x')

info = input("Introduce the equation and the value of /'x' \nEg: x**3+x**2+1 9\n")

infoList = info.split()

equation = infoList[0]
x_value = infoList[1]

exprDerivada = Derivative(equation, x)
resultDerivate = exprDerivada.doit().subs({x:x_value})

The code above gives the result of the first derivate of a function, but the equation is accepted as it comes without the function: eval()

Again, any help is appreciated.

Daniel
  • 147
  • 1
  • 7
  • 19

1 Answers1

1

You are sending a string object that indeed doesn't have a subs property
Use eval(expr).subs(.....) to convert the string to the math expression.
However eval() is a risky stuff to use as it will execute pretty much anything. So be sure to properly secure the user input or you could get you system destroyed by malicious user input. See this answer for a detailed explanation.

Mayeul sgc
  • 1,964
  • 3
  • 20
  • 35
  • @Mayeul_sgc Ok I get it, so is there a less risky solution? Also, I have been doing other operations: I tried to calculate the derivative of a function using the same input method and it doesn't need the function ```eval()```, works fine with this: ```Derivative(equation, x)```, I have update the question, anyway your answer is what I need. – Daniel May 31 '21 at 03:33
  • 1
    You could use `simpleeval` package but i never used it myself. If the answer answers your question don't hesitate to mark as solved – Mayeul sgc May 31 '21 at 03:37
  • You can use sympy's `parse_expr` function. – Oscar Benjamin May 31 '21 at 17:02