Transform string into algorithm

-1

Can anyone tell me if there is a way for me to transform a string into an algorithm? for example: a="1 + 1" = > b = 1 + 1. For simple examples it is quiet to create a string interpreter, the problem is that I will get into more complex things like "(x ** 2 - 1) / (x - 1)".

note: I considered the SymPy library.

    
asked by anonymous 26.05.2018 / 23:33

2 answers

2

You can convert your string to a sympy expression using the parse_expr () function in the sympy.parsing.sympy_parser module.

>>> from sympy.abc import a, b, c
>>> from sympy.parsing.sympy_parser import parse_expr
>>> sympy_exp = parse_expr('(a+b)*40-(c-a)/0.5')
>>> sympy_exp.evalf(subs={a:6, b:5, c:2})
448.000000000000

Source: link

    
27.05.2018 / 00:03
2

Use eval () to evaluate the code and return the best interpretation for it.

a="15 + 2" print (eval (a))

Eval () is so useful, that it even turns strings into variables with it, and there is also 'exec' that executes a string as if it were a code see both working in the same example:

a = 5 b = 8 c = 7

for x in ['a', 'b', 'c']: # Transforms strings into variables.

exec'print(eval(x))'
    
27.05.2018 / 20:51