Created
October 8, 2020 15:11
-
-
Save felixdorn/8d64269dc89066585bacee570c0be670 to your computer and use it in GitHub Desktop.
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
import re | |
PRECEDENCES = {'+': 2, '-': 2, '*': 3, '/': 3, '^': 4} | |
def has_greater_precedence(operator, comparison): | |
return PRECEDENCES[operator] > PRECEDENCES[comparison] | |
def peek(stack): | |
return stack[-1] if len(stack) > 0 else None | |
def parse_expr(expr): | |
tokens = re.findall("[\^+/*()-]|\d+", expr) | |
operators = [] | |
output = [] | |
for token in tokens: | |
if token.isnumeric(): | |
output.append(int(token)) | |
elif token == '(': | |
operators.append(token) | |
elif token == ')': | |
top = peek(operators) | |
while top is not None and top != '(': | |
output.append(operators.pop()) | |
top = peek(operators) | |
operators.pop() | |
else: | |
top = peek(operators) | |
while top is not None and top not in ['(', ')'] and has_greater_precedence(top, token): | |
output.append(operators.pop()) | |
top = peek(operators) | |
operators.append(token) | |
while peek(operators) is not None: | |
output.append(operators.pop()) | |
return output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment