|
@ -7,27 +7,45 @@ class Expression: |
|
|
self.droit = droit |
|
|
self.droit = droit |
|
|
|
|
|
|
|
|
def evalue(self): |
|
|
def evalue(self): |
|
|
if self == None: |
|
|
dfs_post(self) |
|
|
return |
|
|
print(self.valeur) |
|
|
if self.gauche != None: |
|
|
|
|
|
self.gauche.evalue() |
|
|
|
|
|
if self.droit != None: |
|
|
|
|
|
self.droit.evalue() |
|
|
|
|
|
if self.valeur == "+": |
|
|
|
|
|
self.valeur = self.gauche.valeur + self.droit.valeur |
|
|
|
|
|
if self.valeur == "*": |
|
|
|
|
|
self.valeur = self.gauche.valeur * self.droit.valeur |
|
|
|
|
|
|
|
|
|
|
|
def __str__(self): |
|
|
def __str__(self): |
|
|
pass |
|
|
expstr = dfs_in(self, "") |
|
|
|
|
|
return expstr |
|
|
|
|
|
|
|
|
|
|
|
def dfs_post(a): |
|
|
|
|
|
if a == None: |
|
|
|
|
|
return |
|
|
|
|
|
dfs_post(a.gauche) |
|
|
|
|
|
dfs_post(a.droit) |
|
|
|
|
|
if a.valeur == "+": |
|
|
|
|
|
a.valeur = a.gauche.valeur + a.droit.valeur |
|
|
|
|
|
if a.valeur == "*": |
|
|
|
|
|
a.valeur = a.gauche.valeur * a.droit.valeur |
|
|
|
|
|
|
|
|
|
|
|
def dfs_in(a, expstr): |
|
|
|
|
|
if a == None: |
|
|
|
|
|
return expstr |
|
|
|
|
|
expstr = dfs_in(a.gauche, expstr) |
|
|
|
|
|
expstr = expstr + str(a.valeur) |
|
|
|
|
|
expstr = dfs_in(a.droit, expstr) |
|
|
|
|
|
return expstr |
|
|
|
|
|
|
|
|
|
|
|
def npi2tree(exptext): |
|
|
|
|
|
exptext = exptext.split() |
|
|
|
|
|
expression = Pile_chaine() |
|
|
|
|
|
for element in exptext: |
|
|
|
|
|
if element in ("+", "*"): |
|
|
|
|
|
droit = expression.depiler() |
|
|
|
|
|
gauche = expression.depiler() |
|
|
|
|
|
expression.empiler(Expression(element, gauche, droit)) |
|
|
|
|
|
else: |
|
|
|
|
|
expression.empiler(Expression(int(element), None, None)) |
|
|
|
|
|
return expression.sommet() |
|
|
|
|
|
|
|
|
exp = Expression('*', |
|
|
exp = "6 4 3 * +" |
|
|
Expression(6, None, None), |
|
|
exp = npi2tree(exp) |
|
|
Expression('+', |
|
|
|
|
|
Expression(4, None, None), |
|
|
|
|
|
Expression(3, None, None) |
|
|
|
|
|
) |
|
|
|
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
print(exp) |
|
|
exp.evalue() |
|
|
exp.evalue() |
|
|
print(exp.valeur) |
|
|
|