Skip to content

Commit a1aecf5

Browse files
committed
Update domath.py
Added "power of" operators ^ and ** functionality
1 parent f50e33a commit a1aecf5

1 file changed

Lines changed: 23 additions & 7 deletions

File tree

domath.py

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,42 @@
22

33
import ast
44
import sys
5-
from math_evaluator.implicit import calc
5+
import operator
6+
from math_evaluator.explicit import calc as explicit_calc, op_map
7+
from math_evaluator.implicit import calc as implicit_calc, valid_ops, allowed_types
68

79
# This depends entirely on the Math Evaluator package.
810
# see: https://medium.com/@r.harvey/how-i-made-a-math-evaluator-on-24-lines-65afe8e560fd
911
# and the code at: https://github.com/theRealProHacker/MathEvaluator
1012
#
1113

14+
# Support both ** and ^ as power of...
15+
valid_ops.add(ast.Pow)
16+
op_map[ast.BitXor] = operator.__pow__
1217

1318
errmsg = "Malformed equation? The Python package Math Evaluator accepts:\n \
1419
° operands\n \
1520
· ints and\n \
1621
· floats\n \
1722
° operators\n \
18-
· unary +-,\n \
19-
· binary +-*/ and\n \
20-
· parantheses ()"
23+
· unary +-\n \
24+
· binary +-*^**/ and\n \
25+
· parentheses ()"
2126

2227

2328
def domath(equation):
2429
expression = equation
2530
try:
26-
result = calc(equation)
31+
result = implicit_calc(equation)
2732
except Exception as e:
28-
print(f"{expression} errored out with: {e}")
33+
try:
34+
result = explicit_calc(equation)
35+
return(result)
36+
except Exception as e:
37+
print(f"{expression} errored out in explicit_calc with: {e}")
38+
print(f"{errmsg}")
39+
sys.exit(1)
40+
print(f"{expression} errored out in implicit_calc with: {e}")
2941
print(f"{errmsg}")
3042
sys.exit(1)
3143
return(result)
@@ -39,8 +51,12 @@ def main(num_args: int, usage: str):
3951
sys.exit(1)
4052
equation = sys.argv[1]
4153
if equation != None:
42-
print(f"{equation} = {domath(equation)}")
54+
# remove commas & $ signs from any of the numbers, if present
55+
clean_equation_a = equation.replace(",", "")
56+
clean_equation = clean_equation_a.replace("$", "")
57+
print(f"{clean_equation} = {domath(clean_equation)}")
4358
sys.exit()
4459

4560
if __name__ == "__main__":
61+
# print(f"{str(sys.argv[1:])}")
4662
main(2, 'USAGE: script_name <input_equation_in_quotes>')

0 commit comments

Comments
 (0)