Created
June 12, 2022 15:11
-
-
Save blluv/fb4018d1dfe6ce4f7bf5c8bea726c12d to your computer and use it in GitHub Desktop.
check valid expr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ast | |
def checkValid(expr: str): | |
try: | |
tree = ast.parse(expr) | |
except: | |
return False | |
if len(tree.body) != 1: | |
return False | |
if not isinstance(tree.body[0], ast.Expr): | |
return False | |
def check(expr: ast.Expr): | |
if isinstance(expr, (int, float)): | |
return True | |
if isinstance(expr, ast.Name): | |
return True | |
if isinstance(expr, ast.Constant): | |
return check(expr.value) | |
elif isinstance(expr, ast.BinOp): | |
return check(expr.left) and check(expr.right) | |
else: | |
return False | |
return check(tree.body[0].value) | |
assert checkValid("1") == True | |
assert checkValid("(1+2)*(x)") == True | |
assert checkValid('2**4') == True | |
assert checkValid('([]+1)') == False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment