Created
January 13, 2014 04:23
-
-
Save zpconn/8394678 to your computer and use it in GitHub Desktop.
Very simple shunting-yard parser for converting in-fix to post-fix.
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 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