0

I have a list of expressions (+ - *): ["2 + 3", "5 - 1", "3 * 4", ...] and I need to convert every expresion to expression = answer like this 2 + 3 = 5.

I tried just doing print(listt[0]) but it outputs 2 + 3, not 5. So how do i get the answer of this expression? I know that there is a long way by doing .split() with every expression, but is there any other faster way of doing this?

UPD: I need to use only built-in functions

FoxFil
  • 320
  • 10
  • Does this answer your question? [Evaluating a mathematical expression in a string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) - There's a lot better answer there in my opinion, which doesn't use eval. – Cow Jan 24 '23 at 07:04
  • If the expressions only contain a single operator (e.g., +, -, /, *) you will learn a lot more by trying to do this without *eval()*. You'll learn even more if there are multiple operators and you have to implement BODMAS rules – DarkKnight Jan 24 '23 at 07:37

3 Answers3

2

You can use the eval() function from Python Builtins :

for expr in yourlist:
    print(expr, "=", eval(expr))
    # 2+3 = 5

As stated in the comments, this is not malicious-proof. Use this only if you know the string being evaluated are indeed simple arithmetic expressions.

endive1783
  • 827
  • 1
  • 8
  • 18
1

If you want to avoid using eval() (and you probably should) then you could do something like this:

from operator import add, sub, mul, truediv
from re import compile

OMAP = {
    '+': add,
    '-': sub,
    '*': mul,
    '/': truediv
}

pattern = compile(r'^(\d+\.*\d*)\s*(.)\s*(\d+\.*\d*)$')

exprs = ["2 + 3.5", "5 - 1", "3 * 4", "3 / 4"]

def convert(s):
    try:
        return int(s)
    except ValueError:
        pass
    return float(s)

for expr in exprs:
    x, o, y = pattern.findall(expr)[0]
    r = OMAP[o](convert(x), convert(y))
    print(f'{expr} = {r}')

Output:

2 + 3.5 = 5.5
5 - 1 = 4
3 * 4 = 12
3 / 4 = 0.75

Note:

This is not robust as it assumes that the operators are only ever going to be one of +, -, *, / and furthermore that the pattern always matches the regular expression.

Input data changed to include a floating point number

DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

Use eval() function. The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.