Evaluate a simple mathematical expression. Args: expression: A mathematical expression to evaluate (e.g., "2 + 2"). Returns: A dictionary containing the result or error.
(expression: str)
| 65 | |
| 66 | |
| 67 | def calculate(expression: str) -> dict[str, Any]: |
| 68 | """Evaluate a simple mathematical expression. |
| 69 | |
| 70 | Args: |
| 71 | expression: A mathematical expression to evaluate (e.g., "2 + 2"). |
| 72 | |
| 73 | Returns: |
| 74 | A dictionary containing the result or error. |
| 75 | """ |
| 76 | try: |
| 77 | # Only allow safe mathematical operations |
| 78 | allowed_chars = set("0123456789+-*/.() ") |
| 79 | if not all(c in allowed_chars for c in expression): |
| 80 | return {"error": "Invalid characters in expression"} |
| 81 | |
| 82 | result = eval(expression) # Safe due to character restriction |
| 83 | return {"expression": expression, "result": result} |
| 84 | except Exception as e: |
| 85 | return {"expression": expression, "error": str(e)} |
| 86 | |
| 87 | |
| 88 | # Sample queries to try: |