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.
51 lines
1.4 KiB
51 lines
1.4 KiB
import re
|
|
|
|
class Token:
|
|
NUMBER = 0
|
|
OPERATOR = 1
|
|
PARENTHESE = 2
|
|
FUNCTION = 3
|
|
|
|
@staticmethod
|
|
def isNumber(n):
|
|
return re.match(r'\d+', str(n)) is not None
|
|
|
|
@staticmethod
|
|
def getPrecedence(tok):
|
|
if tok == "(" or tok == "":
|
|
return 4
|
|
elif tok == "*" or tok == "/":
|
|
return 3
|
|
elif tok == "+" or tok == "-":
|
|
return 2
|
|
|
|
|
|
def __init__(self, type, val):
|
|
self.type = type
|
|
self.val = val
|
|
|
|
class Expression:
|
|
|
|
def __init__(self, val=None, gauche=None, droite=None):
|
|
if Token.isNumber(val) 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 == "+":
|
|
return self.gauche.evalue() + self.droite.evalue()
|
|
elif self.val == "-":
|
|
return self.gauche.evalue() - self.droite.evalue()
|
|
elif self.val == "*":
|
|
return self.gauche.evalue() * self.droite.evalue()
|
|
elif self.val == "/":
|
|
return self.gauche.evalue() / self.droite.evalue()
|
|
else:
|
|
return float(self.val)
|
|
|
|
def __str__(self):
|
|
if Token.isNumber(self.val):
|
|
return str(self.val)
|
|
return "(" + str(self.gauche.__str__()) + str(self.val) + str(self.droite.__str__()) + ")"
|