Watch: Building a Reverse Polish Notation (RPN) Evaluator in Python

Learn how to build a stack-based evaluator for reverse polish notation expressions using Python

Watch: Building a Reverse Polish Notation (RPN) Evaluator in Python
Image credit: Author

Contents

  1. Reverse Polish Notation (RPN)
  2. Example RPN expressions
  3. Source code
  4. Code walk-through

Reverse Polish Notation (RPN)

Reverse Polish notation (also known as postfix notation) is one of multiple notations for representing mathematical expressions. Most of us are familiar with infix notation, but there are also the less popular prefix and postfix notations.

The most obvious difference among these lie in the position of operators in the expression.

  • Infix: operators are “in” between the operands
  • Prefix: operators are before (pre) the operands
  • Postfix: operators are after (post) the operands

Other differences include the significance of space as a separator (prefix and postfix are space sensitive while infix is not) and the way order of operations is expressed. The order of operation is inherent in the expression structure in prefix and postfix notations while the infix notation requires the use of parentheses to make the order of operations explicit.

# Ambiguity in order of operations for infix notation
1 + 2 + 3
(1 + 2) + 3
1 + (2 + 3)

# No ambiguity in prefix and postfix (using postfix as an example)
# The structure tells us that 1 and 2 are added first, then 3
1 2 + 3 +

Example RPN expressions

# Example 1
1 10 30 + *
1 40 *
40

# Example 2
1 2 + 3 +
3 3 +
6

# Example 3
1 2 - 2 +
-1 2 +
1

# Example 4
1 2 /
0.5

Source code

Code walk-through

Watch the video here

Thank you for watching. Please LIKE and SUBSCRIBE to show your support and watch more videos like this one.

Videos you should watch next

More Computing resources

Watch videos covering a variety of topics in Computing at OnelTalksTech.com