Spaces:
Sleeping
Sleeping
Create tools/math_tool.py
Browse files- tools/tools/math_tool.py +46 -0
tools/tools/math_tool.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import ast
|
| 3 |
+
import operator
|
| 4 |
+
|
| 5 |
+
def safe_eval(expression: str) -> float:
|
| 6 |
+
"""Säkert evaluera matematiska uttryck"""
|
| 7 |
+
# Tillåtna operatorer
|
| 8 |
+
operators = {
|
| 9 |
+
ast.Add: operator.add,
|
| 10 |
+
ast.Sub: operator.sub,
|
| 11 |
+
ast.Mult: operator.mul,
|
| 12 |
+
ast.Div: operator.truediv,
|
| 13 |
+
ast.Pow: operator.pow,
|
| 14 |
+
ast.BitXor: operator.xor,
|
| 15 |
+
ast.USub: operator.neg,
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
def eval_expr(node):
|
| 19 |
+
if isinstance(node, ast.Num):
|
| 20 |
+
return node.n
|
| 21 |
+
elif isinstance(node, ast.BinOp):
|
| 22 |
+
return operators[type(node.op)](eval_expr(node.left), eval_expr(node.right))
|
| 23 |
+
elif isinstance(node, ast.UnaryOp):
|
| 24 |
+
return operators[type(node.op)](eval_expr(node.operand))
|
| 25 |
+
else:
|
| 26 |
+
raise TypeError(node)
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
return eval_expr(ast.parse(expression, mode='eval').body)
|
| 30 |
+
except:
|
| 31 |
+
return None
|
| 32 |
+
|
| 33 |
+
def calculate_math(expression: str) -> str:
|
| 34 |
+
"""Beräkna matematiska uttryck"""
|
| 35 |
+
try:
|
| 36 |
+
# Rensa uttrycket
|
| 37 |
+
clean_expr = re.sub(r'[^0-9+\-*/().\s]', '', expression)
|
| 38 |
+
|
| 39 |
+
result = safe_eval(clean_expr)
|
| 40 |
+
if result is not None:
|
| 41 |
+
return str(result)
|
| 42 |
+
else:
|
| 43 |
+
return f"Cannot calculate: {expression}"
|
| 44 |
+
|
| 45 |
+
except Exception as e:
|
| 46 |
+
return f"Math error: {str(e)}"
|