Control and handle any algebraic expression, as well as do common expression operations such as getting postfix, prefix, and expression tree.
pip install Algebraic-Expression-Parser
from AlgebraicExpressionParser import ExpressionParser
from AlgebraicExpressionParser import Operator
from AlgebraicExpressionParser import Operators
operators = [Operator(symbol='+'), Operator(symbol='-'), Operator(symbol='*', precedence=2), Operator(
symbol='-', type=Operator.unary, precedence=3, associativity=Operator.rtl, position=Operator.prefix), Operator(symbol='^', precedence=4), Operator(symbol='sin', type=Operator.unary, precedence=3, associativity=Operator.rtl, position=Operator.prefix)]
operators = Operators(operators)
parser = ExpressionParser(operators)
parser.postfix('(-3) * (x^3)')
>>> ['3', '-', 'x', '3', '^', '*']
parser.postfix('sin(x)--x')
>>> ['x', 'sin', 'x', '-', '-']
parser.postfix('1^2^3')
>>> ['1', '2', '^', '3', '^']
parser.postfix('1^(2^3)')
>>> ['1', '2', '3', '^', '^']
parser.syntax_tree('(-3) * (x^3)')
>>> Node: (value: *, left: Node: (value: -, left: None, right: Node: (value: 3, left: None, right: None)), right: Node: (value: ^, left: Node: (value: x, left: None, right: None), right: Node: (value: 3, left: None, right: None)))
parser.syntax_tree('(-3) * (x^3)').preorder()
>>> ['*', '-', '3', '^', 'x', '3']
parser.syntax_tree('(-3) * (x^3)').inorder()
>>> ['-', '3', '*', 'x', '^', '3']
parser.syntax_tree('(-3) * (x^3)').postorder()
>>> ['3', '-', 'x', '3', '^', '*']
- Any charcter after it will be handled as variable even if it is a space (only one character, for variables with more than one character use special_variables parameter).
- Characters after it has higher precedence than operators.
parser.postfix('$+ + x')
>>> ['$', '+', 'x', '+']
- A list represents variables other than predefined ones(constants and one symbol variables)
- They have lower precedence than operators.
parser = ExpressionParser(operators, special_variables = {'_'})
parser.postfix('_ * x')
>>> ['_', 'x', '*']