Skip to content

Instantly share code, notes, and snippets.

@DNDK
Created August 13, 2021 20:54
Show Gist options
  • Save DNDK/9517377ae20796ff187febe6154e7f0f to your computer and use it in GitHub Desktop.
Save DNDK/9517377ae20796ff187febe6154e7f0f to your computer and use it in GitHub Desktop.
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