问题
I'm currently working on a modified version of the Shunting Yard Algorithm that would work with variables, but I cant figure out how to get it to work. For example, I would want the algorithm to re-write 2 * (2x + 5) - 5 to 4x + 5. Any ideas / links to already implemented algorithms that does this already?
回答1:
- Take the expression:
2 * (2x + 5) - 5
- Add the * symbol to make it more understandable for the computer:
2 * (2*x + 5) - 5
- Parse it using the Shunting Yard Algorithm, it becomes:
2 2 x * 5 + * 5 -
(Each character could be seen as an element of an array). - With the parsed expression, create the binary tree:
-
/ \
* 5
/ \
2 +
/ \
* 5
/ \
2 x
5. Define and apply algebraic rules to the tree. For example, a rule to be able to 'multiply' the 2
node with the 2 * x + 5
subtree.
来源:https://stackoverflow.com/questions/25320505/shunting-yard-algorithm-with-variables