Skip to content

Instantly share code, notes, and snippets.

@zpconn
Created January 13, 2014 04:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zpconn/8394678 to your computer and use it in GitHub Desktop.
Save zpconn/8394678 to your computer and use it in GitHub Desktop.
Very simple shunting-yard parser for converting in-fix to post-fix.
def postfix(tokens):
output_stack = []
op_stack = []
for token in tokens:
if is_number(token):
output_stack.append(token)
elif token in ['+', '-', '*', '/']:
while len(op_stack) > 0:
if (token in ['+', '-'] and op_stack[-1] in ['*', '/']) or (token in ['*', '/'] and op_stack[-1] in ['*', '/']):
output_stack.append(op_stack.pop())
else:
break
op_stack.append(token)
output_stack += reversed(op_stack)
return output_stack
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
print postfix(['3', '+', '4', '*', '2', '-', '5'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment