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.

71 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: str) -> list:
buffer = ""
tokens = []
for char in text:
#NUMBER
if Token.isNumber(char) or char == ".":
buffer += char
else:
#PUSH
if buffer != "":
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))
return tokens
def shutting_yard(tokens: list) -> File:
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:
while (not opertator.est_vide() and opertator.sommet().val != "(") and (Token.getPrecedence(opertator.sommet().val) > Token.getPrecedence(token.val) or (Token.getPrecedence(token.val) == Token.getPrecedence(opertator.sommet().val) and token.val != "^")):
output.enfiler(opertator.depiler())
opertator.empiler(token)
elif token.val == "(":
opertator.empiler(token)
elif token.val == ")":
while not opertator.est_vide() and opertator.sommet().val != "(":
assert not opertator.est_vide()
output.enfiler(opertator.depiler())
assert opertator.sommet().val == "("
opertator.depiler()
if opertator.sommet().type == Token.FUNCTION:
output.enfiler(opertator.depiler())
while not opertator.est_vide():
assert opertator.sommet().val != "("
output.enfiler(opertator.depiler())
return output
def npi2tree(tokens: File) -> Expression:
pile = Pile()
while not tokens.est_vide():
token = tokens.defiler()
if token.val in ["+", "-", "*", "/"]:
exp = Expression(token.val, pile.depiler(), pile.depiler())
pile.empiler(exp)
else:
pile.empiler(Expression(token.val))
return pile.depiler()
if __name__ == "__main__":
a = npi2tree(shutting_yard(tokenize("2+44*(4+21)"))).evalue()
print(a)
#print(npi2tree(tokenize("6 4 3 + *")))