Last active
April 18, 2018 18:56
-
-
Save guoguo12/dfa2ed858821aa98da57 to your computer and use it in GitHub Desktop.
A concise prefix notation calculator. Read the article at http://aguo.us/writings/prefix-notation.html.
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
#!/usr/bin/env python | |
"""calc.py: A concise prefix notation calculator.""" | |
import regex # pip install regex | |
def calc_eval(exp): | |
"""Evaluates the given prefix notation expression. | |
Raises a SyntaxError if the input is not valid. | |
""" | |
m = regex.match(r'\(([-+\/\*]) ((?R)) ((?R))\)|(\d+)|[-+\/\*]', exp) | |
if not m: | |
raise SyntaxError('Not well formed') | |
if all(map(m.group, [1, 2, 3])): # exp is a procedure call | |
return eval(' '.join([str(calc_eval(m.group(i))) for i in [2, 1, 3]])) | |
return eval(exp) if m.group(4) else exp # exp is a number / an operator | |
""" Run from command line for REPL mode. """ | |
if __name__ == '__main__': | |
while True: | |
print calc_eval(raw_input('> ')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment