Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
postfix-evaluation.First solution in Clear category for Postfix Evaluation by poa
from typing import Union
def postfix_evaluate(items: list[Union[int, str]]) -> int:
stack = []
result = None
i = 0
while i < len(items):
op = items[i]
if type(op) == int:
stack.append(op)
i += 1
continue
b = stack.pop()
a = stack.pop()
if op == "+":
result = a + b
elif op == "-":
result = a - b
elif op == "*":
result = a * b
elif op == "/":
if b == 0:
result = 0
else:
result = a // b
stack.append(result)
i += 1
return stack.pop()
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!")
March 19, 2024