使用栈结构实现表达式求值的代码
时间: 2024-04-29 18:25:02 浏览: 6
好的,以下是使用栈结构实现表达式求值的代码:
```python
def evaluate_expression(exp):
operands = []
operators = []
# define helper function to perform arithmetic operation
def perform_op():
op = operators.pop()
b = operands.pop()
a = operands.pop()
if op == '+':
operands.append(a + b)
elif op == '-':
operands.append(a - b)
elif op == '*':
operands.append(a * b)
elif op == '/':
operands.append(a / b)
# iterate through each character in expression
for char in exp:
# if char is an operand, push to operand stack
if char.isdigit():
operands.append(int(char))
# if char is an operator, push to operator stack
elif char in '+-*/':
while operators and operators[-1] in '*/' and char in '+-':
perform_op()
operators.append(char)
# if char is opening parentheses, push to operator stack
elif char == '(':
operators.append(char)
# if char is closing parentheses, perform operations until opening parentheses is found
elif char == ')':
while operators[-1] != '(':
perform_op()
operators.pop()
# perform remaining operations
while operators:
perform_op()
# return final result
return operands.pop()
```
请问还有其它问题吗?