1.表达式求值问题,应用“栈”编写一个计算器,要求: a)支持整数(长整型范围内)四则混合运算; b)输入应是中缀表达式,对不合法的输入应有提示; c)能够输出正确计算结果; d)示例如输入5(10-3)/7,输出结果5 e)题目编号 HO1
时间: 2024-02-01 19:15:07 浏览: 59
利用栈做计算器(表达式运算)
5星 · 资源好评率100%
以下是使用栈来实现表达式求值的代码,可以满足题目要求:
```python
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty():
raise ValueError("Stack is empty.")
return self.items.pop()
def peek(self):
if self.is_empty():
raise ValueError("Stack is empty.")
return self.items[-1]
def is_operator(char):
return char in "+-*/"
def priority(operator):
if operator in "+-":
return 1
elif operator in "*/":
return 2
else:
return 0
def infix_to_postfix(infix_expr):
stack = Stack()
postfix_list = []
token_list = infix_expr.split()
for token in token_list:
if token.isdigit():
postfix_list.append(token)
elif is_operator(token):
while not stack.is_empty() and priority(stack.peek()) >= priority(token):
postfix_list.append(stack.pop())
stack.push(token)
elif token == "(":
stack.push(token)
elif token == ")":
while stack.peek() != "(":
postfix_list.append(stack.pop())
stack.pop()
while not stack.is_empty():
postfix_list.append(stack.pop())
return " ".join(postfix_list)
def calculate(postfix_expr):
stack = Stack()
token_list = postfix_expr.split()
for token in token_list:
if token.isdigit():
stack.push(int(token))
elif is_operator(token):
operand2 = stack.pop()
operand1 = stack.pop()
if token == "+":
result = operand1 + operand2
elif token == "-":
result = operand1 - operand2
elif token == "*":
result = operand1 * operand2
elif token == "/":
result = operand1 / operand2
else:
raise ValueError("Unknown operator.")
stack.push(result)
if stack.is_empty():
raise ValueError("Invalid expression.")
else:
return stack.pop()
def main():
infix_expr = input("Please enter an infix expression: ")
postfix_expr = infix_to_postfix(infix_expr)
print("Postfix expression:", postfix_expr)
try:
result = calculate(postfix_expr)
print("Result:", result)
except ValueError as e:
print("Error:", e)
if __name__ == "__main__":
main()
```
示例输入:`5*(10-3)/7`
输出结果:`Result: 2.142857142857143`
阅读全文