Skip to content

Instantly share code, notes, and snippets.

@jsocol
Last active March 9, 2017 20:32
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 jsocol/37270ffaef8faa90cef0c2dc8dfa85c4 to your computer and use it in GitHub Desktop.
Save jsocol/37270ffaef8faa90cef0c2dc8dfa85c4 to your computer and use it in GitHub Desktop.
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