Postfix Evaluator

Stack Evaluation Postfix

Postfix Expression Evaluator

In this problem, you are given a string representing a postfix expression (also known as Reverse Polish Notation). The expression contains integers and the operators +, -, *, and /, all separated by spaces. Your task is to evaluate the expression using a stack and return the result as a number.

Requirements

  • Process the string token by token.
  • Use a stack to store numbers.
  • When an operator is encountered, pop the required number of elements from the stack, perform the operation, and push the result back onto the stack.
  • You can assume the input expression is valid.

Example

For the input:

'3 4 + 2 * 7 /'

The evaluation would proceed as follows:

  1. Push 3, push 4.
  2. Encounter +, pop 4 and 3, compute 3 + 4 = 7, push 7.
  3. Push 2.
  4. Encounter *, pop 2 and 7, compute 7 * 2 = 14, push 14.
  5. Push 7.
  6. Encounter /, pop 7 and 14, compute 14 / 7 = 2, push 2.

The function should return 2.

Note: April 25 is ANZAC Day, a day of remembrance. As you write your code, take a moment to reflect on the importance of remembering history while building for the future.