|
|
@ -7,27 +7,45 @@ class Expression: |
|
|
|
self.droit = droit |
|
|
|
|
|
|
|
def evalue(self): |
|
|
|
if self == None: |
|
|
|
return |
|
|
|
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 |
|
|
|
dfs_post(self) |
|
|
|
print(self.valeur) |
|
|
|
|
|
|
|
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('*', |
|
|
|
Expression(6, None, None), |
|
|
|
Expression('+', |
|
|
|
Expression(4, None, None), |
|
|
|
Expression(3, None, None) |
|
|
|
) |
|
|
|
) |
|
|
|
exp = "6 4 3 * +" |
|
|
|
exp = npi2tree(exp) |
|
|
|
|
|
|
|
print(exp) |
|
|
|
exp.evalue() |
|
|
|
print(exp.valeur) |