Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
match operator solution in Clear category for Postfix Evaluation by juestr
import operator
from collections.abc import Callable
def postfix_evaluate(items: list[int | str]) -> int:
def div0(a: int, b: int) -> int:
return a // b if b else 0
def op2(f: Callable[[int, int], int]) -> None:
stack.append(f(stack.pop(-2), stack.pop()))
stack = []
for x in items:
match x:
case "+": op2(operator.add)
case "-": op2(operator.sub)
case "*": op2(operator.mul)
case "/": op2(div0)
case _: stack.append(x)
return stack.pop()
March 1, 2024