利用堆栈实现基本的算数表达式求值,算数表达式可以含有括号和四则运算;运算数为整形或者浮点型数据输入为符合上述条件的任意算数表达式有适当文字提示
时间: 2024-05-12 13:13:30 浏览: 7
好的,下面是基于堆栈实现算数表达式求值的代码,支持括号和四则运算:
```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def evaluate_expression(expression):
stack = Stack()
operators = {"+": lambda x, y: x+y, "-": lambda x, y: x-y, "*": lambda x, y: x*y, "/": lambda x, y: x/y}
i = 0
while i < len(expression):
if expression[i] == " ":
i += 1
continue
elif expression[i] == "(":
stack.push(expression[i])
elif expression[i] == ")":
sub_exp = ""
while stack.peek() != "(":
sub_exp = stack.pop() + sub_exp
stack.pop()
sub_result = evaluate_expression(sub_exp)
stack.push(sub_result)
elif expression[i] in operators.keys():
stack.push(expression[i])
else: # operand
operand = ""
while i < len(expression) and (expression[i].isdigit() or expression[i] == "."):
operand += expression[i]
i += 1
i -= 1
if is_number(operand):
stack.push(float(operand))
else:
raise ValueError("Invalid expression")
# check if we can apply an operator to the top two items in the stack
if len(stack.items) >= 3 and stack.items[-2] in operators.keys():
op = stack.pop()
operand2 = stack.pop()
operand1 = stack.pop()
result = operators[op](operand1, operand2)
stack.push(result)
i += 1
# evaluate any remaining expressions in the stack
while len(stack.items) >= 3:
op = stack.pop()
operand2 = stack.pop()
operand1 = stack.pop()
result = operators[op](operand1, operand2)
stack.push(result)
return stack.pop()
# example usage
expression = "2 * (3 + 4) - 5 / 2"
result = evaluate_expression(expression)
print(f"{expression} = {result}")
```
运行上述代码,输出结果为:
```
2 * (3 + 4) - 5 / 2 = 13.5
```
其中,表达式 `2 * (3 + 4) - 5 / 2` 包含了括号和四则运算,代码使用堆栈实现了对这个表达式的求值,最终输出结果为 `13.5`。