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.

113 lines
3.3 KiB

import re
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 == 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.isNumber(self.val):
return str(self.val)
return "(" + str(self.gauche.__str__()) + str(self.val) + str(self.droite.__str__()) + ")"
class Token:
ADDITION = "+"
MULTIPLICATION = "*"
PARENTHESE_OUVERTE = "("
PARENTHESE_FERME = ")"
NUMBER = re.compile(r'(?:\d+)?.\d+')
@staticmethod
def isNumber(n):
return Token.NUMBER.match(str(n)) is not None
def tokenize(text):
buffer = ""
tokens = []
for char in text:
if Token.isNumber(char):
buffer += char
continue
elif char == " ":
continue
if buffer != "":
tokens.append(buffer)
buffer = ""
tokens.append(char)
if buffer != "":
tokens.append(buffer)
return tokens
def arbre(tokens): #-> Expression
print(tokens)
current = None
waiting_before_exp = None
waiting_for_after_exp = None
i = 0
while i < len(tokens):
if tokens[i] == "(":
j = i + 1
innerBrackets = 1
innerTokens = []
while tokens[j] != ")" and innerBrackets != 0:
if tokens[j] == "(":
innerBrackets += 1
elif tokens[j] == ")":
innerBrackets -= 1
innerTokens.append(tokens[j])
j += 1
exp = arbre(innerTokens)
tokens = tokens[:i] + [" "] + tokens[j+1:]
#i -= j+1
if waiting_for_after_exp != None:
waiting_for_after_exp.droite = exp
waiting_before_exp = waiting_for_after_exp
waiting_for_after_exp = None
else:
waiting_before_exp = exp
elif tokens[i] == "*" or tokens[i] == "+":
exp = Expression("*")
if Token.isNumber(tokens[i-1]):
exp.gauche = tokens[i-1]
if Token.isNumber(tokens[i+1]):
exp.droite = tokens[i+1]
if Token.isNumber(tokens[i-1]) and Token.isNumber(tokens[i+1]):
return exp
if tokens[i-1] == ")":
exp.gauche = waiting_before_exp
waiting_before_exp = None
elif tokens[i+1] == "(":
waiting_for_after_exp = exp
print(exp)
elif tokens[i-1] == " ":
exp.gauche = waiting_before_exp
waiting_for_after_exp = exp
else:
raise Exception()
i += 1
return waiting_for_after_exp
if __name__ == "__main__":
print(arbre(tokenize("(2*8)+(4+7)")))