Last active
February 28, 2020 21:11
-
-
Save gidj/3bff35f59cd259e0d8b1160b94a05de0 to your computer and use it in GitHub Desktop.
Basic RPN implmementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Postfix Notation Calculator | |
# | |
# Postfix notation, is a way of writing mathematical | |
# expressions where each operator is preceded by the | |
# two operands it applies to and looks something | |
# like 2 5 3 + * instead of (5 + 3 ) * 2 | |
# | |
# Write a function that takes a postfix notation expression | |
# returns the result of evaluating the expression. | |
# | |
# Implement the following operators [+, -, *] | |
# | |
# eg. | |
# "3 11 +" -> 14 | |
# "3 11 5 + -" -> -13 | |
# "2 3 11 + 5 - *" -> 18 | |
import collections | |
import operator | |
OPERATORS = { | |
"+": operator.add, | |
"-": operator.sub, | |
"*": operator.mul, | |
} | |
def resolve(string: str) -> int: | |
tokens = string.split(" ") | |
stack = collections.deque() | |
for token in tokens: | |
if token in OPERATORS: | |
op1, op2 = stack.pop(), stack.pop() | |
stack.append(OPERATORS[token](op1, op2)) | |
else: | |
stack.append(int(token)) | |
return stack.pop() | |
tests = [] | |
tests.append("3 11 +") | |
tests.append("3 11 5 + -") | |
tests.append("2 3 11 + 5 - *") | |
for test in tests: | |
print(resolve(test)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment