from misc.expression import Token, Expression from lib.Pile import Pile_chaine as Pile from lib.File import File_chaine as File 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.type == Token.OPERATOR: a, b = pile.depiler(), pile.depiler() t = ((a, b) if token.val != "^" else (b, a)) exp = Expression(token.val, *t) pile.empiler(exp) elif token.type == Token.FUNCTION: exp = Expression(token.val, pile.depiler(), None) pile.empiler(exp) else: pile.empiler(Expression(token.val)) return pile.depiler()