Created
August 8, 2013 13:02
-
-
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)
This file contains hidden or 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 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