Skip to content

Instantly share code, notes, and snippets.

@jamiebullock
Created February 16, 2020 12:58
Show Gist options
  • Save jamiebullock/f53558ce065ba84b95174c777da34112 to your computer and use it in GitHub Desktop.
Save jamiebullock/f53558ce065ba84b95174c777da34112 to your computer and use it in GitHub Desktop.
Calculator using dictionary lookup and recursion
from operator import pow, truediv, mul, add, sub
operators = {
'+': add,
'-': sub,
'*': mul,
'/': truediv
}
def calculate(s):
if s.isdigit():
return float(s)
for c in operators.keys():
left, operator, right = s.partition(c)
if operator in operators:
return operators[operator](calculate(left), calculate(right))
calc = input("Type calculation:\n")
print("Answer: " + str(calculate(calc)))
@kvnandula04
Copy link

kvnandula04 commented Oct 28, 2021

How do you deal with negative inputs?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment