Home > Mobile >  how to check a math expression in a string Python
how to check a math expression in a string Python

Time:10-04

I have a math expression in a string.

So,how can i check is math expression right ?

Maybe there are some ways to do that using Python libraries without creating own functional?

Examples:

exp = "(5 5)-(5) (-2)" #True
exp = "(5 5)/2-1" #True
exp = "(5 5)/(3-1)" #True
exp = "(5 5)/(3-1" #False
exp = "5 " #False
exp = "(5 5)/()" #False
exp = "(a b)/5" #False (only numbers)

CodePudding user response:

You can use the eval function in pandas

import pandas as pd
exp = "(5 5)-(5) (-2)"
pd.eval(exp)

If you intend on using expressions like "(a b)/5" make sure you define the variables like this

a = 1
b = 2
exp = "(a b)/5"
pd.eval(exp)

else the snippet will yield the following error:

UndefinedVariableError: name 'a' is not defined

You can try using this function

def ismath(exp):
    try:
        result = pd.eval(exp)
        return True
    except Exception:
        return False

ismath("(5 5)-(5) (-2)") # Returns True
ismath("(5 5)-(5) (a)") # Returns False
  • Related