-
-
Notifications
You must be signed in to change notification settings - Fork 40.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
18ef157
commit 2f8ab87
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
"""Parse arbitrary math equations in a safe way. | ||
Gratefully copied from https://stackoverflow.com/a/9558001 | ||
""" | ||
import ast | ||
import operator as op | ||
|
||
# supported operators | ||
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, | ||
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor, | ||
ast.USub: op.neg} | ||
|
||
def compute(expr): | ||
"""Parse a mathematical expression and return the answer. | ||
>>> compute('2^6') | ||
4 | ||
>>> compute('2**6') | ||
64 | ||
>>> compute('1 + 2*3**(4^5) / (6 + -7)') | ||
-5.0 | ||
""" | ||
return _eval(ast.parse(expr, mode='eval').body) | ||
|
||
def _eval(node): | ||
if isinstance(node, ast.Num): # <number> | ||
return node.n | ||
elif isinstance(node, ast.BinOp): # <left> <operator> <right> | ||
return operators[type(node.op)](_eval(node.left), _eval(node.right)) | ||
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1 | ||
return operators[type(node.op)](_eval(node.operand)) | ||
else: | ||
raise TypeError(node) |