Home > front end >  How to solve expressions from a list?
How to solve expressions from a list?

Time:01-24

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

CodePudding user response:

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.

CodePudding user response:

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 - 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

  • Related