user8776321
user8776321

Reputation:

Expand and simplify an expression based on a string input

I have an input like "2(5x+4) + 3(2x-1)" in plain text and I need to expand and simplify it. It appears sympy requires it to be entered as a python object made up of python types. Is there a way to automatically parse it / a library that doesn't require it so I can give it the string and it gives me the answer in a human readable format?

Upvotes: 2

Views: 856

Answers (2)

MatsLindh
MatsLindh

Reputation: 52792

sympy already has such a parser built-in under sympy.parsing.sympy_parser.parse_expr. To get the results you want with your input statement you also have to add the implicit_multiplication transformation (since sympy otherwise won't generate statements that make sense for 2( and 5x):

from sympy.parsing.sympy_parser import (
    parse_expr,
    standard_transformations, 
    implicit_multiplication,
)
parse_expr("2(5x+4) + 3(2x-1)", transformations=standard_transformations + (implicit_multiplication,))

Upvotes: 1

Azamat Galimzhanov
Azamat Galimzhanov

Reputation: 638

You want to use sympify function, for your expression it's gonna be like this:

sympify('2*(5*x+4) + 3*(2*x-1)')

Upvotes: 0

Related Questions