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.

79 lines
2.5 KiB

from expression import Token, Expression
from lib.Pile import Pile_chaine as Pile
from lib.File import File_chaine as File
def tokenize(text):
buffer = ""
tokens = []
for char in text:
#NUMBER
if Token.isNumber(char) or char == ".":
buffer += char
else:
#PUSH
if buffer != "":
print("a")
tokens.append(Token(Token.NUMBER, buffer))
buffer = ""
#SINGLE CHAR
if char != " ":
if char == "(" or char == ")":
tokens.append(Token(Token.PARENTHESE, char))
else:
tokens.append(Token(Token.OPERATOR, char))
if buffer != "":
tokens.append(Token(Token.NUMBER, buffer))
for token in tokens:
print(token.type, ":", token.val)
return tokens
def shutting_yard(tokens):
output = File()
opertator = Pile()
for token in tokens:
if token.type == Token.NUMBER:
output.enfiler(token)
elif token.type == Token.FUNCTION:
opertator.empiler(token)
elif token.type == Token.OPERATOR:
if not opertator.est_vide():
o2 = opertator.sommet()
a = o2 != "("
print(o2.val)
b = Token.getPrecedence(o2.val) > Token.getPrecedence(token.val)
c = Token.getPrecedence(token.val) == Token.getPrecedence(o2.val)
while a and (b or (c)): #and d))
output.enfiler(opertator.depiler())
opertator.empiler(token)
elif token.val == "(":
opertator.empiler(token)
elif token.val == ")":
while opertator.sommet() != "(":
assert not opertator.est_vide()
output.enfiler(opertator.depiler())
assert opertator.sommet() == "("
opertator.depiler()
if opertator.sommet().type == Token.FUNCTION:
output.enfiler(opertator.depiler())
while not opertator.est_vide():
assert opertator.sommet != "("
output.enfiler(opertator.depiler())
return output
def npi2tree(tokens):
pile = Pile()
for token in tokens:
if token in ["+", "-", "*", "/"]:
exp = Expression(token, pile.depiler(), pile.depiler())
pile.empiler(exp)
else:
pile.empiler(Expression(token))
return pile.depiler()
if __name__ == "__main__":
print(shutting_yard(tokenize("2+44(4+21)")))
#print(npi2tree(tokenize("6 4 3 + *")))