Created
July 28, 2021 18:23
-
-
Save grevych/f122a4dbe33caf16f74d8da2518b5ede to your computer and use it in GitHub Desktop.
Polish notation using two stacks
This file contains 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
def solve(polish_notation): | |
polish_notation = polish_notation.split() | |
operands = [] | |
operators = [] | |
operations = { | |
'+': lambda x, y: x + y, | |
'-': lambda x, y: x - y, | |
'*': lambda x, y: x * y, | |
'/': lambda x, y: x / y | |
} | |
last_read = None | |
for element in polish_notation: | |
if element.isdigit(): | |
operands.append(int(element)) | |
while len(operands) > 1 and last_read.isdigit(): | |
second = operands.pop() | |
first = operands.pop() | |
operator = operators.pop() | |
operands.append(operations[operator](first, second)) | |
else: | |
operators.append(element) | |
last_read = element | |
return operands.pop() | |
if __name__ == '__main__': | |
print(solve('* + 3 5 - 7 2')) | |
print(solve('- * / 15 - 7 + 1 1 3 + 2 + 1 1')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment