From ec8c10ac1bd939bd210d1047f4d9d7c4dfca456d Mon Sep 17 00:00:00 2001 From: Zach White Date: Tue, 26 May 2020 13:05:41 -0700 Subject: [CLI] Add a subcommand for getting information about a keyboard (#8666) You can now use `qmk info` to get information about keyboards and keymaps. Co-authored-by: Erovia --- lib/python/qmk/math.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 lib/python/qmk/math.py (limited to 'lib/python/qmk/math.py') diff --git a/lib/python/qmk/math.py b/lib/python/qmk/math.py new file mode 100644 index 0000000000..88dc4a300c --- /dev/null +++ b/lib/python/qmk/math.py @@ -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): # + return node.n + elif isinstance(node, ast.BinOp): # + return operators[type(node.op)](_eval(node.left), _eval(node.right)) + elif isinstance(node, ast.UnaryOp): # e.g., -1 + return operators[type(node.op)](_eval(node.operand)) + else: + raise TypeError(node) -- cgit v1.2.3