Last active
March 9, 2017 20:32
-
-
Save jsocol/37270ffaef8faa90cef0c2dc8dfa85c4 to your computer and use it in GitHub Desktop.
An implementation of http://www.cs.csi.cuny.edu/~zelikovi/csc326/data/assignment5.htm#_ftnref1
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
from __future__ import division, print_function, unicode_literals | |
import operator | |
import re | |
import sys | |
WHITESPACE_RE = re.compile(r'\s+') | |
NUMBER_RE = re.compile(r'-?\d+(\.\d+)?') | |
OPERATORS = { | |
'+': operator.add, | |
'-': operator.sub, | |
'*': operator.mul, | |
'/': operator.truediv, | |
'^': operator.pow, | |
} | |
def parse_input(s): | |
return [n.strip() for n in WHITESPACE_RE.split(s)] | |
def process_operator(stack, op): | |
oper = OPERATORS.get(op) | |
if not oper: | |
raise Exception('Invalid operation: %s' % op) | |
right = stack.pop() | |
left = stack.pop() | |
result = oper(left, right) | |
stack.append(result) | |
def do_math(formula): | |
stack = [] | |
for n in parse_input(formula): | |
if NUMBER_RE.match(n): | |
stack.append(float(n)) | |
elif n in OPERATORS: | |
process_operator(stack, n) | |
elif n == '=': | |
return stack[0] | |
raise Exception("No '=' in %s" % formula) | |
def main(): | |
print('Enter an expression or # to quit.') | |
while True: | |
line = raw_input('> ') | |
line = line.strip() | |
if line == '#': | |
break | |
try: | |
print('%g' % do_math(line)) | |
except Exception as exc: | |
print('Error!', exc) | |
print('Goodbye!') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment