import math def rpn(tokens): stack = [] # Iterate through each token in the list of tokens for token in tokens: # Check if the token is an operator (+, -, *, /) if token in "+-*/": # Pop the last two numbers from the stack number2 = stack.pop() number1 = stack.pop() # Perform the arithmetic operation based on the operator if token == "+": result = number1 + number2 elif token == "-": result = number1 - number2 elif token == "*": result = number1 * number2 else: # token == "/" result = math.trunc(number1 / number2) # Push the result back onto the stack stack.append(result) else: # If the token is a number, convert it to an integer and push onto the stack stack.append(int(token)) # The final result will be the only item remaining on the stack return stack.pop() # Driver code def main(): inputs = [ ["2", "1", "+", "3", "*"], # (2 + 1) * 3 = 9 ["4", "13", "5", "/", "+"], # 4 + (13 / 5) = 6 ["10", "6", "9", "3", "/", "-", "*"], # (10 * (6 - (9 / 3))) = 30 ["1", "1", "+", "2", "*"], # (1 + 1) * 2 = 4 ["3", "5", "8", "*", "+", "13", "-"], # (3 + (5 * 8)) - 13 = 30 ] for i in range(len(inputs)): print(i + 1, ". Input tokens = ", inputs[i], sep="") print(" Result = ", rpn(inputs[i]), sep="") print("-" * 100) if __name__ == "__main__": main()