Originally Posted by
howlingmadhowie
Just to add some more grit to the mill, transforming in real time from "normal" to rpn is not quite trivial. take for example:
3 * (4 + 5)
which is 27
here's how to transform it to rpn (my thoughts are written in bash-style comments):
Code:
3 * (4 + 5) # 3 is okay at the start, but then comes a star,
# that's no good, let's move it to the right
3 ( * 4 + 5) # eek! not good, the * has to go to after the
# brackets. let's find the end of the balancing bracket
3 (4 + 5) * # okay, that's better, but i haven't yet dealt with
# the bracket. the 4 is okay, but the + isn't
3 (4 5 +) * # perfect, well sort of.
the result should be:
3 4 5 + *
This method will fall apart if you put the operations in a different order though. For example:
Code:
3 + 4 * 5 # 3 is good, + isn't, so move it to the right
3 4 + * 5 # not enough arguments for a *, so move it to the right
3 4 + 5 * # perfect, valid post-fix syntax
7 5 * # evaluate 3 4 +
35 # evaluate 7 5 *
So the answer is 35. But wait a minute, 3 + 4 * 5 is 23! Darn that order of operations!
You can't just blindly move things to the right, compensating for parentheses. You would also need to check for the natural order of operations when building the tree, which adds to the complexity not insignificantly.
Bookmarks