Created
February 16, 2020 12:58
-
-
Save jamiebullock/f53558ce065ba84b95174c777da34112 to your computer and use it in GitHub Desktop.
Calculator using dictionary lookup and recursion
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
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))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do you deal with negative inputs?