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.

70 lines
2.0 KiB

import re
2 years ago
from math import cos, sin, exp, sqrt
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()
2 years ago
elif self.val == "^":
return self.gauche.evalue() ** self.droite.evalue()
elif self.val == "cos":
return cos(self.gauche.evalue())
elif self.val == "sin":
return sin(self.gauche.evalue())
elif self.val == "exp":
return exp(self.gauche.evalue())
elif self.val == "sqrt":
return sqrt(self.gauche.evalue())
else:
return float(self.val)
def __str__(self):
if Token.isNumber(self.val):
return str(self.val)
2 years ago
return "(" + str(self.gauche.__str__()) + str(self.val) + str(self.droite.__str__()) + ")"
class Token:
NUMBER = 0
OPERATOR = 1
PARENTHESE = 2
FUNCTION = 3
@staticmethod
def isChar(n):
return re.match(r'[a-z]', str(n)) is not None
@staticmethod
def isNumber(n):
return re.match(r'\d+', str(n)) is not None
@staticmethod
def getPrecedence(tok):
if tok == "(" or 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
def __str__(self):
return self.val