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| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Tools:
|
| 9 |
+
|
| 10 |
+
def __init__(self):
|
| 11 |
+
self.citation = True
|
| 12 |
+
|
| 13 |
+
def calculator(self, equations: str) -> str:
|
| 14 |
+
"""
|
| 15 |
+
Calculate the result of a simple equation or comparison.
|
| 16 |
+
:param equation: The equation to calculate or compare.
|
| 17 |
+
- For arithmetic operations: Use operators like +, -, *, /, **, //, %
|
| 18 |
+
- For comparisons: Use operators like >, <, >=, <=, ==, !=
|
| 19 |
+
- For solving systems of equations, separate equations with a semicolon (e.g., 'x + y = 30; 2*x + 4*y = 80')
|
| 20 |
+
- Evaluating multiple expressions separated by commas (e.g., '-1/27, 19/52')
|
| 21 |
+
- Example inputs: "3 + 5", "10 / 2", "e ** 2", "pi > 3", "3.11 < 3.8"
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
# 预处理:自动添加乘号
|
| 25 |
+
modified_equations = re.sub(r"(\d)([a-zA-Z])", r"\1*\2", equations)
|
| 26 |
+
modified_equations = modified_equations.replace("^", "**")
|
| 27 |
+
|
| 28 |
+
# 检测和解决方程组
|
| 29 |
+
if "=" in modified_equations:
|
| 30 |
+
try:
|
| 31 |
+
# 分割多个方程(如果有的话)
|
| 32 |
+
eq_list = modified_equations.split(";")
|
| 33 |
+
if len(eq_list) > 1:
|
| 34 |
+
# 检测到多个方程,作为方程组求解
|
| 35 |
+
equations_sym = []
|
| 36 |
+
symbols = set()
|
| 37 |
+
for eq in eq_list:
|
| 38 |
+
left_expr, right_expr = eq.split("=")
|
| 39 |
+
left_sym = sp.sympify(left_expr)
|
| 40 |
+
right_sym = sp.sympify(right_expr)
|
| 41 |
+
symbols |= left_sym.free_symbols | right_sym.free_symbols
|
| 42 |
+
equations_sym.append(left_sym - right_sym)
|
| 43 |
+
|
| 44 |
+
solution = sp.solve(equations_sym, list(symbols))
|
| 45 |
+
|
| 46 |
+
# 格式化输出结果为“变量 = 解”的形式
|
| 47 |
+
solution_str = ", ".join(
|
| 48 |
+
f"{str(var)} = {sol}" for var, sol in solution.items()
|
| 49 |
+
)
|
| 50 |
+
return f"The solution to the system of equations '{equations}' is {solution_str}. Provide this solution to the user."
|
| 51 |
+
else:
|
| 52 |
+
# 单个方程,正常求解
|
| 53 |
+
left_expr, right_expr = eq_list[0].split("=")
|
| 54 |
+
left_sym = sp.sympify(left_expr)
|
| 55 |
+
right_sym = sp.sympify(right_expr)
|
| 56 |
+
symbols = list(left_sym.free_symbols | right_sym.free_symbols)
|
| 57 |
+
if len(symbols) != 1:
|
| 58 |
+
return f"The equation '{equations}' contains {len(symbols)} variables. Please provide an equation with only one variable."
|
| 59 |
+
|
| 60 |
+
solution = sp.solve(left_sym - right_sym, symbols[0])
|
| 61 |
+
return f"The solution to the equation '{equations}' is {symbols[0]} = {solution[0]}. Provide this solution to the user."
|
| 62 |
+
except Exception as e:
|
| 63 |
+
return f"There was an error solving the equation(s) '{equations}': {str(e)}. Notify the user about the issue."
|
| 64 |
+
|
| 65 |
+
ops = {
|
| 66 |
+
ast.Add: operator.add,
|
| 67 |
+
ast.Sub: operator.sub,
|
| 68 |
+
ast.Mult: operator.mul,
|
| 69 |
+
ast.Div: operator.truediv,
|
| 70 |
+
ast.Pow: operator.pow,
|
| 71 |
+
ast.Mod: operator.mod,
|
| 72 |
+
ast.FloorDiv: operator.floordiv,
|
| 73 |
+
ast.BitXor: operator.xor,
|
| 74 |
+
ast.BitAnd: operator.and_,
|
| 75 |
+
ast.BitOr: operator.or_,
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
unary_ops = {
|
| 79 |
+
ast.UAdd: operator.pos,
|
| 80 |
+
ast.USub: operator.neg,
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
compare_ops = {
|
| 84 |
+
ast.Gt: operator.gt,
|
| 85 |
+
ast.Lt: operator.lt,
|
| 86 |
+
ast.GtE: operator.ge,
|
| 87 |
+
ast.LtE: operator.le,
|
| 88 |
+
ast.Eq: operator.eq,
|
| 89 |
+
ast.NotEq: operator.ne,
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
def eval_expr(node):
|
| 93 |
+
if isinstance(node, ast.Num):
|
| 94 |
+
return node.n
|
| 95 |
+
elif isinstance(node, ast.Constant):
|
| 96 |
+
return node.value
|
| 97 |
+
elif isinstance(node, ast.Tuple): # 处理元组输入
|
| 98 |
+
return tuple(eval_expr(elt) for elt in node.elts)
|
| 99 |
+
elif isinstance(node, ast.Name):
|
| 100 |
+
if node.id == "pi":
|
| 101 |
+
return math.pi
|
| 102 |
+
elif node.id == "e":
|
| 103 |
+
return math.e
|
| 104 |
+
else:
|
| 105 |
+
raise ValueError(f"Unsupported constant: {node.id}")
|
| 106 |
+
elif isinstance(node, ast.BinOp):
|
| 107 |
+
if type(node.op) in ops:
|
| 108 |
+
return ops[type(node.op)](
|
| 109 |
+
eval_expr(node.left), eval_expr(node.right)
|
| 110 |
+
)
|
| 111 |
+
else:
|
| 112 |
+
raise ValueError(f"Unsupported operation: {type(node.op).__name__}")
|
| 113 |
+
elif isinstance(node, ast.UnaryOp):
|
| 114 |
+
if type(node.op) in unary_ops:
|
| 115 |
+
return unary_ops[type(node.op)](eval_expr(node.operand))
|
| 116 |
+
else:
|
| 117 |
+
raise ValueError(
|
| 118 |
+
f"Unsupported unary operation: {type(node.op).__name__}"
|
| 119 |
+
)
|
| 120 |
+
elif isinstance(node, ast.Compare):
|
| 121 |
+
if len(node.ops) == 1:
|
| 122 |
+
op = node.ops[0]
|
| 123 |
+
if type(op) in compare_ops:
|
| 124 |
+
return compare_ops[type(op)](
|
| 125 |
+
eval_expr(node.left), eval_expr(node.comparators[0])
|
| 126 |
+
)
|
| 127 |
+
else:
|
| 128 |
+
raise ValueError(f"Unsupported comparison: {type(op).__name__}")
|
| 129 |
+
else:
|
| 130 |
+
raise ValueError("Unsupported multiple comparisons")
|
| 131 |
+
else:
|
| 132 |
+
raise ValueError(f"Unsupported expression type: {type(node).__name__}")
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
parsed = ast.parse(modified_equations, mode="eval")
|
| 136 |
+
result = eval_expr(parsed.body)
|
| 137 |
+
if isinstance(result, bool):
|
| 138 |
+
return f"The comparison '{equations}' evaluates to {result}. Respond accordingly."
|
| 139 |
+
else:
|
| 140 |
+
return f"The result of the expression '{equations}' is {result}. Provide this information to the user."
|
| 141 |
+
except (SyntaxError, ValueError) as e:
|
| 142 |
+
return f"There is an error in the expression '{equations}': {str(e)}. Notify the user about the issue."
|
| 143 |
+
except ZeroDivisionError:
|
| 144 |
+
return f"The expression '{equations}' involves a division by zero, which is undefined. Inform the user about this error."
|
| 145 |
+
except Exception as e:
|
| 146 |
+
return f"The expression '{equations}' is invalid: {str(e)}. Let the user know that there was a mistake."
|