Skip to content

Instantly share code, notes, and snippets.

@gtklocker
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save gtklocker/9262323 to your computer and use it in GitHub Desktop.

Select an option

Save gtklocker/9262323 to your computer and use it in GitHub Desktop.
Basic calculator
import operator
def compute(expression):
fn = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.div
}
# could use fn.keys but dictionaries are orderless
operations = ['+', '-', '*', '/']
for operation in operations:
needle = expression.find(operation)
if needle >= 0:
return fn[expression[needle]](compute(expression[:needle]), compute(expression[needle + 1:]))
try:
return float(expression)
except:
raise SyntaxError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment