class Term:
def __init__(self, variable=None, const=None):
self.variable = variable
self.const = const
self.tree = []
@classmethod
def const(cls, const):
term = cls(None, const)
return term
@classmethod
def var(cls, variable):
term = cls(variable, None)
return term
def __call__(self, **kwargs):
return Term.calculate(Term.exchange(self.tree, **kwargs))
def __add__(self, other):
term = Term()
term.tree.append("+")
term.tree.append(self.variable)
if len(other.tree) is not 0:
term.tree.append(other.tree)
else:
term.tree.append(other.variable)
return term
def __sub__(self, other):
term = Term()
term.tree.append("-")
term.tree.append(self.variable)
if len(other.tree) is not 0:
term.tree.append(other.tree)
else:
term.tree.append(other.variable)
return term
def __mul__(self, other):
term = Term()
term.tree.append("*")
term.tree.append(self.variable)
if len(other.tree) is not 0:
term.tree.append(other.tree)
else:
term.tree.append(other.variable)
return term
def __str__(self):
return Term.to_string(self.tree)
@staticmethod
def exchange(tree, **kwargs):
if isinstance(tree[1], str) or isinstance(tree[2], str):
if isinstance(tree[1], str):
for key, value in kwargs.items():
if tree[1] == str(key):
tree[1] = value
if isinstance(tree[2], str):
for key, value in kwargs.items():
if tree[2] == str(key):
tree[2] = value
return (tree[0], tree[1], tree[2])
elif isinstance(tree[2], tuple):
return Term.exchange((tree[0], tree[1], Term.exchange(tree[2])))
@staticmethod
def calculate(tree):
if isinstance(tree[2], int):
if tree[0] == "+":
return tree[1] + tree[2]
elif tree[0] == "-":
return tree[1] - tree[2]
elif tree[0] == "*":
return tree[1] * tree[2]
else:
return Term.calculate((tree[0], tree[1], Term.calculate(tree[2])))
@staticmethod
def to_string(tree):
if not isinstance(tree[2], list):
return "({0} {1} {2})".format(tree[1], tree[0], tree[2])
else:
return Term.to_string((tree[0], tree[1], Term.to_string(tree[2])))
if __name__ == "__main__":
x = Term.var("x")
y = Term.var("y")
z = Term.var("z")
d = x + y
print(d(x=1, y=2))