Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Dict dispatch solution in Clear category for Postfix Evaluation by amandel
from typing import Union
from operator import add, floordiv, mul, sub
def postfix_evaluate(items: list[Union[int, str]]) -> int:
op = { '+':add, '-':sub, '*':mul, '/':floordiv}
stack = []
for x in items:
if isinstance(x, int):
stack.append(x)
else:
a = stack.pop()
try:
stack.append(op[x](stack.pop(), a))
except:
stack.append(0)
return stack[0]
print("Example:")
print(postfix_evaluate([1, 2, "+"]))
# These "asserts" are used for self-checking
assert postfix_evaluate([2, 3, "+", 4, "*"]) == 20
assert postfix_evaluate([2, 3, 4, "*", "+"]) == 14
assert postfix_evaluate([3, 3, 3, "-", "/", 42, "+"]) == 42
print("The mission is done! Click 'Check Solution' to earn rewards!")
Dec. 11, 2023