Evaluating the reverse polish notation
Problem
Given the list of strings consisting of the asthmatic equation expressed in the Reverse Polish notation.Write the program that evaluates the equation and returns the result.
Example:
For {"4","1","+","2.5","*"}, output =12.5
{"5", "80","40","/","+"} = 7
Answer
This question is similar to a previous question, "Evaluating arithmetic equation" but is simpler because the priority among operator had been handled already.
First of all we first need to understand Reverse Polish notation. (Read this link before proceed).
Based on Reverse polish notation, {"4","1","+","2.5","*"} equals to $(4+1) \times 2.5$ while {"5", "80","40","/","+"} is equivalent to $5+(80/40)$.
We can use the stack to solve this problem. Here is the rough algorithm:
1. Iterate over the list of strings.
2. If the current string is a number, push back the number into the stack
3. If the number is operator, take 2 numbers from the stack and compute the result before pushing back the result into the stack.
4. Return the number left on the top of the stack.
The running time of this algorithm is $O(N)$
Here is the complete code.
Practice statistics
19:05: hand-wrote the solution
02:27; validate the solution
21:33: write the code in IDE (3 typos found through compilation)
3:00: fixed the logical flaw after understanding what "Reverse Polish Notation" was
UPDATE (07-17-2019): solved the problem again in python.
Here is the solution in python
Statistics:First of all we first need to understand Reverse Polish notation. (Read this link before proceed).
Based on Reverse polish notation, {"4","1","+","2.5","*"} equals to $(4+1) \times 2.5$ while {"5", "80","40","/","+"} is equivalent to $5+(80/40)$.
We can use the stack to solve this problem. Here is the rough algorithm:
1. Iterate over the list of strings.
2. If the current string is a number, push back the number into the stack
3. If the number is operator, take 2 numbers from the stack and compute the result before pushing back the result into the stack.
4. Return the number left on the top of the stack.
The running time of this algorithm is $O(N)$
Here is the complete code.
Practice statistics
19:05: hand-wrote the solution
02:27; validate the solution
21:33: write the code in IDE (3 typos found through compilation)
3:00: fixed the logical flaw after understanding what "Reverse Polish Notation" was
UPDATE (07-17-2019): solved the problem again in python.
Here is the solution in python
30:00: I think I spent around 20-30 mins with minor typos. Should not happen next time.
UPDATE(2022-06-14): Solved the question again in python
15:17: to write up the code
Comments
Post a Comment