Created
August 13, 2021 20:54
-
-
Save DNDK/9517377ae20796ff187febe6154e7f0f to your computer and use it in GitHub Desktop.
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
import re | |
import sys | |
class ExpressionError(Exception): | |
def __init__(self): | |
super().__init__() | |
def __str__(self): | |
return "Error" | |
def add(a, b): | |
return a+b | |
def sub(a, b): | |
return a-b | |
def mult(a, b): | |
return a*b | |
def div(a, b): | |
try: | |
return a/b | |
except ZeroDivisionError: | |
return float("inf") | |
operations = { | |
"+": add, | |
"-": sub, | |
"*": mult, | |
"/": div | |
} | |
def calculate(exp): | |
ar_exp = re.split("\+|\-|\*|\/", exp) | |
if not len(ar_exp) == 2: | |
raise ExpressionError() | |
oper = exp[1] | |
func = operations.get(oper) | |
if func is not None: | |
try: | |
return func(int(ar_exp[0]), int(ar_exp[1])) | |
except: | |
raise ExpressionError() | |
else: | |
raise ExpressionError() | |
if __name__ == "__main__": | |
exp = sys.argv[1] | |
try: | |
print(calculate(exp)) | |
except ExpressionError: | |
print("Error") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment