Stack Evaluates Reverse Polish Notation
Postfix expressions evaluate with one stack: push numbers, pop two operands per operator, and the final remainder is the whole expression's value.
Code
def evaluate(tokens: list[str]) -> int:
stack: list[int] = []
operators = {"+", "-", "*", "/"}
for token in tokens:
if token in operators:
right = stack.pop()
left = stack.pop()
if token == "+":
stack.append(left + right)
elif token == "-":
stack.append(left - right)
elif token == "*":
stack.append(left * right)
else:
# postfix division truncates toward zero
stack.append(int(left / right))
else:
stack.append(int(token))
return stack.pop()
print(evaluate(["2", "3", "+"])) # 2 + 3
print(evaluate(["5", "1", "2", "+", "4", "*", "+", "3", "-"])) # 5 + (1 + 2) * 4 - 3
print(evaluate(["7", "2", "/"])) # truncating divisionOutput
Captured from a sandboxed run of this snippet in the build pipeline.
5
14
3What the run performs
Stack Evaluates Reverse Polish Notation keeps everything in the function evaluate.
Iteration happens inside for token in tokens — everything outside it runs once.
Caveats
- Every API in play comes with the platform, so nothing has to be installed.
Applying it
This file revolves around the signature: def evaluate(tokens: list[str]) -> int
Import evaluate from the file and call it — the rest of the code is implementation detail.
Statements that matter
elif token == "-":
stack.append(left - right)
elif token == "*":
stack.append(left * right)
Interactive Tools for This Topic
Scientific Notation ConverterConvert numbers between plain decimal and scientific notation, optionally fixing the significant digits and splitting out the mantissa and exponent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text ReverserReverse text by characters, words, or lines, counting Unicode code points so emoji stay intact.
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `evaluate` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.