Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Solution: Reverse Polish calculator (stack) with deque

from collections import deque

stack = deque()

while True:
    val = input(':')

    if val == 'x':
        break

    if val == '+':
        a = stack.pop()
        b = stack.pop()
        stack.append(a+b)
        continue

    if val == '*':
        a = stack.pop()
        b = stack.pop()
        stack.append(a*b)
        continue


    if val == '=':
        print(stack.pop())
        continue

    stack.append(float(val))