📅  最后修改于: 2023-12-03 15:10:19.691000             🧑  作者: Mango
给定一个仅包含数字的字符串,使用堆栈数据结构对其进行求值。字符串仅包含以下字符:
"1 + 2 * 3"
7
堆栈数据结构是一种非常适合对表达式进行求值的数据结构。具体实现思路如下:
def eval(expression):
# 定义运算符优先级
priority = {'+': 1, '-': 1, '*': 2, '/': 2}
# 定义操作数堆栈 S 和运算符堆栈 O
S, O = [], []
# 遍历表达式中的每一个元素
for elem in expression:
if elem.isdigit():
# 如果该元素是数字,将其压入 S
S.append(int(elem))
elif elem == '(':
# 如果该元素是左括号,将其压入 O
O.append(elem)
elif elem == ')':
# 如果该元素是右括号
while O[-1] != '(':
operator = O.pop()
operand2, operand1 = S.pop(), S.pop()
if operator == '+':
result = operand1 + operand2
elif operator == '-':
result = operand1 - operand2
elif operator == '*':
result = operand1 * operand2
elif operator == '/':
result = operand1 / operand2
S.append(result)
O.pop()
else:
# 如果该元素是运算符
while len(O) > 0 and priority[O[-1]] >= priority[elem]:
operator = O.pop()
operand2, operand1 = S.pop(), S.pop()
if operator == '+':
result = operand1 + operand2
elif operator == '-':
result = operand1 - operand2
elif operator == '*':
result = operand1 * operand2
elif operator == '/':
result = operand1 / operand2
S.append(result)
O.append(elem)
# 处理剩余运算符
while len(O) > 0:
operator = O.pop()
operand2, operand1 = S.pop(), S.pop()
if operator == '+':
result = operand1 + operand2
elif operator == '-':
result = operand1 - operand2
elif operator == '*':
result = operand1 * operand2
elif operator == '/':
result = operand1 / operand2
S.append(result)
# 返回表达式的求值结果
return S.pop()
本文介绍了如何使用堆栈数据结构对表达式进行求值,并给出了具体实现思路和代码实现。堆栈数据结构在表达式求值中有着广泛的应用,读者可以在实际编程中尝试应用此方法。