Skip to content

Instantly share code, notes, and snippets.

@felixdorn
Created October 8, 2020 15:11
Show Gist options
  • Save felixdorn/8d64269dc89066585bacee570c0be670 to your computer and use it in GitHub Desktop.
Save felixdorn/8d64269dc89066585bacee570c0be670 to your computer and use it in GitHub Desktop.
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