Transform String into Algorithm

Asked

Viewed 146 times

-2

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

note: I considered the Sympy library.

  • 1

    Do you want a numerical expression evaluator? In C# you can use CodeDom https://www.c-sharpcorner.com/article/codedom-calculator-evaluating-C-Sharp-math-expressions-dynamica/

  • Exactly. However I look for python. But thank you.

2 answers

3

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

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

Eval() is so useful, you can even turn strings into variables with it, and there is also exec that executes a string as if it were 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))'

2

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

>>> 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: https://stackoverflow.com/a/13225555/194717

  • 1

    Ok, I found a simple way too. Eval. example: x = 0; print(Eval('x * 1 + 2'));

  • 2

    I would just take a little care with the Val. The discussion in the accepted answer of this question is interesting, worth taking a look. https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice

Browser other questions tagged

You are not signed in. Login or sign up in order to post.