Evaluate a postfix expression from a calculator

Write codeEasy12 minBloomberg style

Your task

An old desk calculator stores each formula in postfix form, also called reverse Polish notation. Every operator comes after the values it works on, so no brackets are needed.

Write eval_rpn(tokens) that returns the value of the expression.

Input and output:

  • tokens: a list of 1 to 10,000 strings. Each one is an operator (+, -, * or /) or an integer in decimal, possibly with a leading -.
  • Returns the value as an integer.

Rules:

  • Read the tokens left to right. Each operator replaces the two most recent values with its result: the older value is the left side and the newer one is the right side.
  • A token is an operator only when it is exactly one of the four symbols, so a token like -3 is a number.
  • Division truncates toward zero, so a negative quotient rounds up toward 0.
  • The expression is always valid: every operator has two values to work on, exactly one value is left at the end, and nothing is divided by zero.
  • Every value along the way fits in a signed 32-bit integer, from -2,147,483,648 to 2,147,483,647.

Examples

eval_rpn(tokens: list[str]) -> int
Example 1
Inputeval_rpn(["2", "1", "+", "3", "*"])
Output9
Example 2
Inputeval_rpn(["5", "1", "2", "+", "4", "*", "+", "3", "-"])
Output14
Example 3
Inputeval_rpn(["-7", "2", "/"])
Output-3