Skip to content

Instantly share code, notes, and snippets.

@exallium
Created August 8, 2013 13:02
Show Gist options
  • Select an option

  • Save exallium/6184377 to your computer and use it in GitHub Desktop.

Select an option

Save exallium/6184377 to your computer and use it in GitHub Desktop.
Infix to prefix parser and evaluator I wrote in like 10 minutes (meaning don't judge me)
import sys
# Note ('s are not currently supported. Given we treat them as
# 'frames' they are implicitly simple to recursivly implement.
ops = ['^', '*', '/', '+', '-']
# 1 + 2 -> + 1 2
# 1 + 2 * 3 -> + * 3 2 1
def parser(tokens):
stack = []
op_stack = []
for op in ops:
for i, token in enumerate(tokens):
if op == token:
stack.append(i)
if i + 1 not in stack: stack.append(i + 1)
if i - 1 not in stack: stack.append(i - 1)
return [tokens[i] for i in stack]
# XXX: Note this only does integer mathematics.
def prefix_eval(tokens):
result = None
op = None
resolve = {
'^': lambda x,y: x ** y,
'*': lambda x,y: x * y,
'/': lambda x,y: x / y,
'+': lambda x,y: x + y,
'-': lambda x,y: x - y,
}
for token in tokens:
if token in ops:
op = token
elif result is not None:
result = resolve[op](int(result), int(token))
else:
result = int(token)
return result
if __name__ == '__main__':
parsed = parser(sys.argv[1].split())
print parsed
print prefix_eval(parsed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment