You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
1.1 KiB
38 lines
1.1 KiB
import re
|
|
|
|
class Token:
|
|
OPERAND_ADDITION = "+"
|
|
OPERAND_MULTIPLICATION = "*"
|
|
NUMBER = re.compile(r'\d+') #CHANGER
|
|
|
|
class Expression:
|
|
|
|
def __init__(self, val, gauche=None, droite=None):
|
|
if Token.NUMBER.search(str(val)) is not None and (gauche != None or droite != None):
|
|
raise AttributeError("gauche et droite ne peuvent pas exister si val est un nombre")
|
|
self.val = val
|
|
self.gauche = gauche
|
|
self.droite = droite
|
|
|
|
def evalue(self):
|
|
if self.val == Token.OPERAND_ADDITION:
|
|
return self.gauche.evalue() + self.droite.evalue()
|
|
elif self.val == Token.OPERAND_MULTIPLICATION:
|
|
return self.gauche.evalue() * self.droite.evalue()
|
|
else:
|
|
return int(self.val)
|
|
|
|
def __str__(self):
|
|
if Token.NUMBER.match(string=self.val) is not None:
|
|
return self.val
|
|
return "(" + self.gauche.__str__() + self.val + self.droite.__str__() + ")"
|
|
|
|
|
|
exp = Expression('*',
|
|
Expression(6, None, None),
|
|
Expression('+',
|
|
Expression(4, None, None),
|
|
Expression(3, None, None)
|
|
))
|
|
print(exp.evalue())
|
|
print(str(exp))
|