结果
表达式: 12/(6-2)+3
预期结果: 6 | 实际结果: 6.0
推理过程:
步骤1: 计算:6.0-2.0 = 4.0,新表达式:4.0
步骤2: 替换括号:(6-2) → 4.0,新表达式:12/4.0+3
步骤3: 计算:12.0/4.0 = 3.0,新表达式:3.0+3
步骤4: 计算:3.0+3.0 = 6.0,新表达式:6.0
==================================================
表达式: 2*(3+4*(5-1))
预期结果: 38 | 实际结果: 38.0
推理过程:
步骤1: 计算:5.0-1.0 = 4.0,新表达式:4.0
步骤2: 替换括号:(5-1) → 4.0,新表达式:2*(3+4*4.0)
步骤3: 计算:4.0*4.0 = 16.0,新表达式:3+16.0
步骤4: 计算:3.0+16.0 = 19.0,新表达式:19.0
步骤5: 替换括号:(3+4*4.0) → 19.0,新表达式:2*19.0
步骤6: 计算:2.0*19.0 = 38.0,新表达式:38.0
==================================================
表达式: 2*(3.5+4*(5.2-1))
预期结果: 40.6 | 实际结果: 40.6
推理过程:
步骤1: 计算:5.2-1.0 = 4.2,新表达式:4.2
步骤2: 替换括号:(5.2-1) → 4.2,新表达式:2*(3.5+4*4.2)
步骤3: 计算:4.0*4.2 = 16.8,新表达式:3.5+16.8
步骤4: 计算:3.5+16.8 = 20.3,新表达式:20.3
步骤5: 替换括号:(3.5+4*4.2) → 20.3,新表达式:2*20.3
步骤6: 计算:2.0*20.3 = 40.6,新表达式:40.6
==================================================
import re
def evaluate_expression(expr):
steps = []
expr = expr.replace(' ', '') # 去除空格
# 递归处理括号
while True:
bracket_match = re.search(r'\(([^()]+)\)', expr)
if not bracket_match:
break
sub_expr = bracket_match.group(1)
start, end = bracket_match.span()
sub_result, sub_steps = evaluate_expression(sub_expr)
steps.extend(sub_steps)
new_expr = expr[:start] + str(sub_result) + expr[end:]
steps.append(f"替换括号:({sub_expr}) → {sub_result},新表达式:{new_expr}")
expr = new_expr
# 处理乘除运算
while True:
match = re.search(r'([\d.]+)([*\/])([\d.]+)', expr)
if not match:
break
num1 = float(match.group(1))
op = match.group(2)
num2 = float(match.group(3))
result = num1 * num2 if op == '*' else num1 // num2
start, end = match.span()
new_expr = expr[:start] + str(result) + expr[end:]
steps.append(f"计算:{num1}{op}{num2} = {result},新表达式:{new_expr}")
expr = new_expr
# 处理加减运算
while True:
match = re.search(r'([\d.]+)([+-])([\d.]+)', expr)
if not match:
break
num1 = float(match.group(1))
op = match.group(2)
num2 = float(match.group(3))
result = num1 + num2 if op == '+' else num1 - num2
start, end = match.span()
new_expr = expr[:start] + str(result) + expr[end:]
steps.append(f"计算:{num1}{op}{num2} = {result},新表达式:{new_expr}")
expr = new_expr
return float(expr), steps
# 测试案例
test_cases = [
("3+5*2", 13),
("(10-4)*2+5", 17),
("12/(6-2)+3", 6),
("2*(3+4*(5-1))", 38),
("2*(3.5+4*(5.2-1))", 40.6)
]
for expr, expected in test_cases:
result, steps = evaluate_expression(expr)
print(f"表达式: {expr}")
print(f"预期结果: {expected} | 实际结果: {result}")
print("推理过程:")
for i, step in enumerate(steps, 1):
print(f"步骤{i}: {step}")
print("\n" + "=" * 50 + "\n")