Queue and Stack for Reverse Polish Notation - Python Programming Exercise

In this exercise, you will develop a Python program to evaluate expressions written in Reverse Polish Notation (RPN) using a queue and stack. This exercise is perfect for practicing data structures, queue and stack operations, and arithmetic operations in Python. By implementing this program, you will gain hands-on experience in handling data structures, queue and stack operations, and arithmetic operations in Python. This exercise not only reinforces your understanding of data structures but also helps you develop efficient coding practices for managing user interactions.

 Category

Memory Management Techniques

 Exercise

Queue And Stack For Reverse Polish Notation

 Objective

Develop a Python program to evaluate expressions written in Reverse Polish Notation (RPN) using a queue and stack. The program should use a stack to store operands and a queue to process the operators. Implement operations to handle addition, subtraction, multiplication, and division, ensuring proper handling of the RPN format.

 Example Python Exercise

 Copy Python Code
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.

 Share this Python Exercise

 More Python Programming Exercises of Memory Management Techniques

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Working with ArrayList

    In this exercise, you will develop a Python program to demonstrate the use of an ArrayList-like structure. This exercise is perfect for practicing data structu...

  •  ArrayList Copying a Text File

    In this exercise, you will develop a Python program that uses an ArrayList-like structure (a list) to duplicate the contents of a text file. This exercise is p...

  •  Calculating an Unlimited Sum

    In this exercise, you will develop a Python program to calculate an unlimited sum by continuously adding numbers provided by the user. This exercise is perfect...

  •  ArrayList - Reading a Text File

    In this exercise, you will develop a Python program that uses an ArrayList-like structure (a list) to read and store the contents of a text file. This exercise...

  •  Hash Table - Implementing a Dictionary

    In this exercise, you will develop a Python program that implements a hash table using a dictionary. This exercise is perfect for practicing data structures, d...

  •  Parenthesis Matching

    In this exercise, you will develop a Python program that checks if parentheses in a given expression are properly balanced. This exercise is perfect for practi...