0

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)
The Singularity
2,7785 gold badges29 silver badges63 bronze badges
asked Oct 4, 2021 at 9:58

2 Answers 2

1

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
answered Oct 4, 2021 at 10:00
Sign up to request clarification or add additional context in comments.

Comments

1

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

  1. 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)

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

  1. Use a regex to limit input to eval() to only strings made up exclusively or math characters

  2. make the function call like so: eval(expr, {}, {}) such that the eval function will not have access to the program's global and local variables (which it doesn't need in the first place).

answered Oct 4, 2021 at 20:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.