import abc
class Expression(abc.ABC):
@abc.abstractmethod
def evaluate(self):
pass
@abc.abstractmethod
def simplify(self):
pass
class Number(Expression):
def __init__(self, num):
self.num = num
def evaluate(self):
return self.num
def simplify(self):
return ascii(self.num)
class Variable(Expression):
def __init__(self, var, num):
self.var = var
self.num = num
def evaluate(self):
return self.num
def simplify(self):
return self.var
class Parenthersis(Expression):
def __init__(self, express):
self.express = express
def evaluate(self):
return self.express.evaluate()
def simplify(self):
return "(" + self.express.simplify() + ")"
class Operator(Expression):
pass
class Addition(Operator):
def __init__(self, right, left):
self.left, self.right = left, right
def evaluate(self):
return self.left.evaluate() + self.right.evaluate()
def simplify(self):
if self.left.simplify == "0":
return self.right.simplify()
elif self.right.simplify() == "0":
return self.left.simplify()
elif self.left.simplify == "0" and self.right.simplify() == "0":
return "0"
return self.left.simplify() + "+" + self.right.simplify()
class Multiplication(Operator):
def __init__(self, right, left):
self.left, self.right = left, right
def evaluate(self):
return self.left.evaluate() * self.right.evaluate()
def simplify(self):
if self.left.simplify == "1":
return self.right.simplify()
elif self.right.simplify() == "1":
return self.left.simplify()
elif self.left.simplify == "1" and self.right.simplify() == "1":
return "1"
return self.left.simplify() + "*" + self.right.simplify()
# Test
# 5*(a+2)*b+a
a = Variable("a", 1)
b = Variable("b", 2)
num2 = Number(2)
num5 = Number(5)
sub = Multiplication(b, Parenthersis(Addition(num2,a)))
exp = Addition(a, Multiplication(sub,num5))
print(exp.simplify())
print(exp.evaluate())
# Test
# a*b*(0+a)*1
a = Variable("a", 1)
b = Variable("b", 0)
num1 = Number(1)
num0 = Number(0)
sub = Multiplication(b, Parenthersis(Addition(num0,a)))
exp = Addition(a, Multiplication(sub,num1))
print(exp.simplify())
print(exp.evaluate())