Ejercicio
Cola Y Pila Para Notación Polaca Inversa
Objectivo
Desarrollar un programa Python para evaluar expresiones escritas en notación polaca inversa (RPN) utilizando una cola y una pila. El programa debe utilizar una pila para almacenar operandos y una cola para procesar los operadores. Implementar operaciones para manejar la suma, la resta, la multiplicación y la división, asegurando el manejo adecuado del formato RPN.
Ejemplo de ejercicio de Python
Mostrar código Python
import queue
class RPNCalculator:
"""Class to evaluate expressions in Reverse Polish Notation (RPN)."""
def __init__(self):
"""Initializes the stack and the queue."""
self.stack = [] # Stack to store operands
self.operator_queue = queue.Queue() # Queue to process operators
def evaluate(self, expression):
"""Evaluates an RPN expression."""
tokens = expression.split() # Split the expression into tokens
for token in tokens:
if token.isdigit() or self.is_float(token):
# If the token is a number, push it onto the stack
self.stack.append(float(token))
else:
# If the token is an operator, process it from the queue
self.operator_queue.put(token)
self.process_operator()
# The result should be the only item left in the stack
if len(self.stack) == 1:
return self.stack[0]
else:
raise ValueError("Invalid RPN expression.")
def process_operator(self):
"""Processes the operator from the queue and performs the operation."""
if not self.operator_queue.empty():
operator = self.operator_queue.get() # Get the operator from the queue
# Ensure that there are at least two operands on the stack
if len(self.stack) < 2:
raise ValueError("Insufficient operands for operation.")
operand2 = self.stack.pop() # Pop the second operand
operand1 = self.stack.pop() # Pop the first operand
# Perform the operation
if operator == "+":
result = operand1 + operand2
elif operator == "-":
result = operand1 - operand2
elif operator == "*":
result = operand1 * operand2
elif operator == "/":
if operand2 == 0:
raise ZeroDivisionError("Division by zero.")
result = operand1 / operand2
else:
raise ValueError(f"Unknown operator: {operator}")
# Push the result onto the stack
self.stack.append(result)
def is_float(self, value):
"""Checks if a string represents a valid float."""
try:
float(value)
return True
except ValueError:
return False
def main():
"""Main function to interact with the RPN calculator."""
rpn_calculator = RPNCalculator()
while True:
expression = input("Enter an RPN expression (or type 'exit' to quit): ")
if expression.lower() == 'exit':
print("Exiting the program.")
break
try:
result = rpn_calculator.evaluate(expression)
print(f"Result: {result}")
except (ValueError, ZeroDivisionError) as e:
print(f"Error: {e}")
# Run the program
if __name__ == "__main__":
main()
Output
Enter an RPN expression (or type 'exit' to quit): 3 4 + 2 *
Result: 14.0
Enter an RPN expression (or type 'exit' to quit): 5 1 2 + 4 * + 3 -
Result: 14.0
Enter an RPN expression (or type 'exit' to quit): 10 2 /
Result: 5.0
Enter an RPN expression (or type 'exit' to quit): 2 0 /
Error: Division by zero.
Enter an RPN expression (or type 'exit' to quit): exit
Exiting the program.
Código de ejemplo copiado
Comparte este ejercicio de Python