← Stack Discipline

Micro-Drill #272 — Evaluate Reverse Polish Notation

Stack Discipline Target: 15s

RPN evaluation: numbers push, operators pop two and push result. Note: pop order is b, a (right operand first).

stack = []
for tok in tokens:
    if tok in '+-*/':
        b, a = stack.pop(), stack.pop()
        if tok == '+': stack.append(a + b)
        elif tok == '-': stack.append(a - b)
        elif tok == '*': stack.append(a * b)
        else: stack.append(int(a / b))
    else:
        stack.append(int(tok))

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #271 Micro #273 →