Вот программа на Python, которая предлагает пользователю ввести инфиксное выражение и выводит результат:
import re
def evaluate_expression(expression):
# Remove any whitespaces from the expression
expression = expression.replace(" ", "")
# Convert the expression to postfix notation
postfix = infix_to_postfix(expression)
# Evaluate the postfix expression
result = evaluate_postfix(postfix)
return result
def infix_to_postfix(expression):
# Define the operator precedence
precedence = {"+": 1, "-": 1, "*": 2, "/": 2}
# Initialize an empty stack and an empty postfix list
stack = []
postfix = []
# Split the expression into tokens
tokens = re.findall("[+\-*/()]|\d+", expression)
for token in tokens:
if token.isdigit():
# If the token is a number, append it to the postfix list
postfix.append(token)
elif token == "(":
# If the token is an opening parenthesis, push it to the stack
stack.append(token)
elif token == ")":
# If the token is a closing parenthesis, pop operators from the stack and append them to the postfix list
while stack and stack[-1] != "(":
postfix.append(stack.pop())
stack.pop() # Discard the opening parenthesis
else:
# If the token is an operator, pop operators from the stack and append them to the postfix list
# until an operator with lower precedence is encountered or the stack is empty
while stack and stack[-1] != "(" and precedence[token] <= precedence.get(stack[-1], 0):
postfix.append(stack.pop())
stack.append(token)
# Pop any remaining operators from the stack and append them to the postfix list
while stack:
postfix.append(stack.pop())
# Return the postfix expression as a string
return " ".join(postfix)
def evaluate_postfix(expression):
# Initialize an empty stack
stack = []
# Split the expression into tokens
tokens = expression.split()
for token in tokens:
if token.isdigit():
# If the token is a number, convert it to an integer and push it to the stack
stack.append(int(token))
else:
# If the token is an operator, pop the top two elements from the stack,
# perform the operation, and push the result back to the stack
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
stack.append(result)
# The final result is the top element of the stack
return stack[0]
# Prompt the user to enter an infix expression
expression = input("Enter an infix expression: ")
# Evaluate the expression and print the result
result = evaluate_expression(expression)
print("Result:", result)
Эта программа использует алгоритм Shunting Yard для преобразования инфиксного выражения в постфиксную запись, а затем вычисляет постфиксное выражение с помощью стека.