将计算也使用栈

This commit is contained in:
lsy2246 2024-06-08 12:35:01 +08:00
parent 15d8317298
commit 16ffcccddf

View File

@ -51,33 +51,26 @@ def format_data(data):
while _static_tmp: while _static_tmp:
formula.append(_static_tmp.pop(-1)) formula.append(_static_tmp.pop(-1))
return formula numbers_stack = []
while formula:
single_item = formula.pop(0)
def compute(formula): if single_item.isdigit():
if len(formula) == 1: numbers_stack.append(single_item)
return formula[0]
else: else:
for index, item in enumerate(formula): number2 = float(numbers_stack.pop(-1))
if item in ['+', '-', '*', '/', '%']: number1 = float(numbers_stack.pop(-1))
match item: match single_item:
case '+': case '+':
formula[index - 2] = float(formula[index - 2]) + float(formula[index - 1]) numbers_stack.append(number1 + number2)
case '-': case '-':
formula[index - 2] = float(formula[index - 2]) - float(formula[index - 1]) numbers_stack.append(number1 - number2)
case '*': case '*':
formula[index - 2] = float(formula[index - 2]) * float(formula[index - 1]) numbers_stack.append(number1 * number2)
case '/': case '/':
formula[index - 2] = float(formula[index - 2]) / float(formula[index - 1]) numbers_stack.append(number1 / number2)
case '%': case '%':
formula[index - 2] = float(formula[index - 2]) % float(formula[index - 1]) numbers_stack.append(number1 % number2)
formula.pop(index - 1) return numbers_stack[0]
formula.pop(index - 1)
formula = compute(formula)
return formula
Equation = "1+2/2+(3*3+2)"
Equation = "3%2" print(format_data(Equation))
formula = format_data(Equation)
result = compute(formula)
print(result)