📅  最后修改于: 2023-12-03 14:58:23.905000             🧑  作者: Mango
'门| Gate IT 2008 |问题2' 是针对 Gate IT 2008 考试中的问题2的一个程序。
问题2要求实现一个程序,该程序对一个给定的表达式进行求值操作。输入的表达式包含了整数、运算符、括号和空格。程序需要按照给定的优先级和结合性规则进行求值,输出表达式的结果。
下面是一个简要的解决方案的示例代码,用于实现对给定表达式的求值操作。
def evaluate_expression(expression):
# Remove whitespace from the expression
expression = expression.replace(" ", "")
# Evaluate the expression using a stack and two queues
operators = []
operands = []
for char in expression:
if char.isdigit():
operands.append(int(char))
elif char == "+":
operators.append(char)
elif char == "-":
operators.append(char)
elif char == "*":
operators.append(char)
elif char == "/":
operators.append(char)
elif char == "(":
operators.append(char)
elif char == ")":
# Evaluate the expression within the parentheses
while operators[-1] != "(":
operand2 = operands.pop()
operand1 = operands.pop()
operator = operators.pop()
result = perform_operation(operator, operand1, operand2)
operands.append(result)
operators.pop() # Remove the "(" symbol
while operators:
operand2 = operands.pop()
operand1 = operands.pop()
operator = operators.pop()
result = perform_operation(operator, operand1, operand2)
operands.append(result)
return operands[0]
def perform_operation(operator, operand1, operand2):
if operator == "+":
return operand1 + operand2
elif operator == "-":
return operand1 - operand2
elif operator == "*":
return operand1 * operand2
elif operator == "/":
return operand1 / operand2
# Example usage
expression = "2 + 3 * (4 - 1)"
result = evaluate_expression(expression)
print(result)
'门| Gate IT 2008 |问题2' 是一个求值给定表达式的程序。通过使用栈和队列的数据结构,可以按照给定的规则对表达式进行求值。以上示例代码提供了一个简单的解决方案,但根据实际要求,可能需要进一步修改或扩展该代码。