Using sympy on strings

274 views Asked by At

I have a file with some equations. I want to solve them using sympy. I can use open('problems.txt',mode='r') to open the file. But how to proceed with sympy? I'm getting following error

sympy.core.sympify.SympifyError: Sympify of expression 'could not parse 'x+x+x-x = 18 + 4'' failed, because of exception being raised: SyntaxError: invalid syntax (, line 1)

I'm using Python 3.4.2

1

There are 1 answers

0
Bjoern Dahlgren On

parse_expr should be able to get you going:

import sympy

from sympy.parsing.sympy_parser import (
    parse_expr, standard_transformations,
    implicit_multiplication_application
)

s = 'x+x+x-x = 18 + 4'

def my_parse(s, transfm=None):
    lhs, rhs = s.split('=')
    if transfm is None:
        transfm = (standard_transformations +
            (implicit_multiplication_application,))
    return sympy.Eq(
        parse_expr(lhs, transformations=transfm),
        parse_expr(rhs, transformations=transfm))

expr = my_parse(s)
print(expr)

output:

2*x == 22

using sympy version 0.7.6