![]()
def calculate(s: str) -> float:
def helper(s_iter):
stack = []
num = 0.0
sign = '+'
while True:
char = next(s_iter, None)
if char is None or char in '+-*/)':
if sign == '+':
stack.append(num)
elif sign == '-':
stack.append(-num)
elif sign == '*':
stack.append(stack.pop() * num)
elif sign == '/':
stack.append(stack.pop() / num)
if char is None or char == ')':
break
sign = char
num = 0.0
elif char == '(':
num = helper(s_iter)
elif char.isdigit() or char == '.':
# 处理数字和小数点
num_str = char
while True:
next_char = next(s_iter, None)
if next_char is None or not (next_char.isdigit() or next_char == '.'):
s_iter = itertools.chain([next_char], s_iter) if next_char is not None else s_iter
break
num_str += next_char
num = float(num_str)
return sum(stack)
import itertools
return helper(iter(s.replace(' ', '')))
# 测试示例
expression = "2+3.1 * 4-8.2/2"
print(f"输入: {expression}")
print(f"输出: {calculate(expression)}") # 输出: 10.3
# 测试带括号的表达式
expression_with_parentheses = "2+3.1*(4-8.2)/2"
print(f"\n输入(带括号): {expression_with_parentheses}")
print(f"输出: {calculate(expression_with_parentheses)}") # 输出: -2.521