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.

75 lines
1.4 KiB

from Pile import Pile_chaine
class Expression:
def __init__(self, valeur, gauche, droit):
self.valeur = valeur
self.gauche = gauche
self.droit = droit
def evalue(self):
if self.valeur == '+':
self.valeur = self.gauche.evalue() + self.droit.evalue()
if self.valeur == '*':
self.valeur = self.gauche.evalue() * self.droit.evalue()
return self.valeur
def __str__(self):
if self.gauche is None and self.droit is None:
return str(self.valeur)
expr = ""
if self.gauche is not None:
if self.gauche.valeur in ['+', '*']:
expr += "(" + str(self.gauche) + ")"
else:
expr += str(self.gauche)
expr += " " + str(self.valeur) + " "
if self.droit is not None:
if self.droit.valeur in ['+', '*']:
expr += "(" + str(self.droit) + ")"
else:
expr += str(self.droit)
return expr
def npi2tree(ch):
ch = ch.split()
Expr = Pile_chaine()
for elmt in ch:
if elmt == '*' or elmt == '+':
exp = Expression(elmt, Expr.depiler(), Expr.depiler())
Expr.empiler(exp)
else:
Expr.empiler(Expression(int(elmt), None, None))
return Expr.sommet()
ch1 = '7 4 3 * +'
exp = npi2tree(ch1)