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)
2 Answers 2
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
Comments
As @Luke has suggested, eval() can be used, but I think it's important to expand due to the risks associated with the use of eval - especially with user-controlled input.
2 big reasons to pre-filter input with a regex pattern
In order to filter out expressions that contain anything other than valid mathematical expressions (without variables), you will want to first perform a regex filter, only passing to
eval()strings which contain only characters that are valid in a math-context (which was part of your question)The second reason to use a regex, is that
eval()can be very dangerous when users are able to inject arbitrary values as direct input. By limiting to only the characters valid in a math equation, your risk is reduced significantly
The Regex itself
You can validate that inputs match a pattern along the lines of: r'^[\d+-/*()]+$' (example here)
While the version above wouldn't account for syntactically incorrect operations (e.g. "(5+5)/(3-1", "5+" or "(5+5)/()"), you should be able to play with it to improve filtering.
... or just catch the errors from eval() that result from invalid math
More on security
This page gives some more context/examples of the risks of eval() as well as some ways to mitigate.
tl;dr
Use a regex to limit input to
eval()to only strings made up exclusively or math charactersmake the function call like so:
eval(expr, {}, {})such that the eval function will not have access to the program'sglobalandlocalvariables (which it doesn't need in the first place).