I am given 2 y 5 1 4 3 - * - * +, and am asked to evaluate it, and then draw the equivalent expression tree. I haven't done any work with this before, can someone show the steps you would take to solve this type of question?
I have looked at: Post order traversal of a formula
and am confused as to how to come to that answer.
What you are given is a postfix expression. It is well-known that these things are evaluated with stacks according to the following rule:
Working left to right, when you encounter a value, push it. When you encounter an operator, pop the top two values, apply the operation, and push the result back.
So your expression evaluation proceeds like this
2 (push 2)
2 y (push y)
2 y 5 (push 5)
2 y 5 1 (push 1)
2 y 5 1 4 (push 4)
2 y 5 1 4 3 (push 3)
2 y 5 1 1 (pop 3, pop 4, push 4-3)
2 y 5 1 (pop 1, pop 1, push 1*1)
2 y 4 (pop 1, pop 5, push 5-1)
2 4y (pop 4, pop y, push y*4)
2+4y (pop 4y, pop 2, push 2+4y)
Your answer is the value left on the stack.
Now, you asked about producing a tree also. To produce a tree, rather than evaluating the expression when you find an operator, you "apply" the operator by building a tree fragment with the operator as the root, and the popped tree fragments as children.
So after pushing
2 y 5 1 4 3
you see a -, so you pop the 4 and 3 and you push back this structure
-
/ \
4 3
Next you see the * so you pop the top tree fragment and the one below it, which is actually a tree fragment consisting of the single node
1
So it will look like
*
/ \
1 -
/ \
4 3
You should be able to take it from here.
The answer at Post order traversal of a formula says find the first operator. In your case it is '-'. The second step he describes is put it between the previous two operands.
In your case these two operands are 4 and 3 (they are directly before the '-'). So the formula after this step becomes:
2 y 5 1 (4-3) * - * +
Remember that the expression (4-3) is now one operand.
We apply the steps again to this formula. We see that the first operator now is ''.
The two operands before the '' are 1 and (4-3). The formula becomes:
2 y 5 (1*(4-3)) - * +
Now you can apply this untill all operators are gone.
I will not continue giving more steps because probably this is a homework question. However I think it is clear?
As stated by novalis from the question you linked, scan for the first operator and previous 2 operands and then replace that group with a more familiar expression in parentheses, ie.
if you have:
op1 op2 operator
4 3 -
this becomes:
(op1 operator op2)
(4 - 3 )
so, proceeding...
2 y 5 1 4 3 - * - * +
2 y 5 1 (4 - 3) * - * +
2 y 5 (1 * (4 - 3)) - * +
Proceed in a similar fashion to build the tree. Scan for the first operator and create a tiny tree:
-
/ \
4 3
Then, each new operand is the top node of your new tree:
*
/ \
1 -
/ \
4 3
and then:
-
/ \
5 *
/ \
1 -
/ \
4 3
Related
What postfix expression does the following infix expression translate to?
2 + 3 - 4 / 3 * 3 + 4
I'm really confused on how does it translate to 2 3 4 3 / 3 * - + 4 +?.
Can somebody explain it, please?
Thanks in advance
Put parens around the infix to show order of operations honoring precedence and associativity:
((2 + 3) - ((4 / 3) * 3)) + 4
Now you can use this to draw a syntax tree:
+
_________/ \_
| |
- 4
_/ \____
| |
+ *
/ \ _/ \_
2 3 | |
'/' 3
/ \
4 3
Now you can get postfix by traversing the tree in post order:
2 3 + 4 3 / 3 * - 4 +
There are other post orders that give the right answer. For example, you can get more by choosing to evaluate either the left or the right subtree first for each commutative operator. Equivalently, you can reverse the left and right hand subtrees for each commutative operator and always use a standard, left child first post order search.
You can check the order by executing it with a stack machine:
Stack
read 2, push 2 [2
read 3, push 3 [2 3
read +, pop 3, pop 2, push 5 (i.e. 2 + 3) [5
read 4, push 4 [5 4
read 3, push 3 [5 4 3
read /, pop 3, pop 4, push 1.33... (i.e. 4/3) [5 1.33...
read 3, push 3 [5 1.33... 3
read *, pop 3, pop 1.33..., push 4 (i.e. 1.33... * 3)[5 4
read -, pop 4, pop 5, push 1 (i.e. 5 - 4) [1
read 4, push 4 [1 4
read +, pop 4, pop 1, push 5 (i.e. 1 + 4) [5
So 5 is the answer, which agrees with the infix evaluation.
Recently I have went through some sites,
for converting the Infix to Prefix notation and finally got tucked up.
I have given the steps which I have done..
Ex:- (1+(2*3)) + (5*6) + (7/8)
Method 1:- (Manual Conversion without any algorithm):-
Step1: (1+(*23)) + (*56) + (/78)
Step2: (+1*23) + (*56) + (/78)
Step3: +(+1*23)(*56) + (/78)
Step4: +[+(+1*23)(*56)](/78)
Step5: +++1*23*56/78 **--- Final Ans -----**
Method 2:-
As per the site http://scanftree.com/Data_Structure/infix-to-prefix
Step1: Reverse it:-
) 8 / 7 ( + ) 6 * 5 ( + ) ) 3 * 2 ( + 1 (
Step2: Replace the '(' by ')' and vice versa:
( 8 / 7 ) + ( 6 * 5 ) + ( ( 3 * 2 ) + 1 )
Step3: Convert the expression to postfix form:-
8 7 / 6 5 * + 3 2 * 1 + +
Step4: Reverse it
+ + 1 * 2 3 + * 5 6 / 7 8 --- Final Ans -----
So, here I got totally hanged.
Could any one please provide some light on following things:-
On where I went wrong in the above 2 methods
Which is the right answer
so I can able to understand the concept more better.
Your method is not correct, look at the comment, it says that ( a + b ) + c = a + ( b + c ) . What about (a + b) * c? (a + b) * c != a + (b * c).
According to your manual algorithm, you put the last + is placed to the front. It is not correct. If you use * instead of last + , where did you put it ? Just think about that, then you can easily find the problem with your algorithm.
Another algorithm for solving this problem is just parenthesis it before proceeding. Replace every left parenthesis with the operator inside it.
Example, ((1+(2*3)) + ((5*6) + (7/8))) then it become ++1*23+*56+/78. Your algorithm is correct if the precedence of the operator inside is same. If it is not it will fail.
NOTE : Your answer can also be obtained by the arrangement of parenthesis. (((1+(2*3)) + (5*6)) + (7/8)) then it becomes +++1*23*56/78. But if the last one is * instead of + then it doesn't work.
(b * b - 4 * a * c ) / (2 * c) EQUATION--1;
Now I will solve this mathematically by substituting different variables, and doing 2 terms at time.
=> x=bb* ; y=4a* ; z=2c*
these above are the substitution of first time, use in eq 1
( x - y * c )/(z)
again doing the substitutions with new variables.
=> i=yc* ;
(x - i)/z
=> j=xi-;
j/z
Now this here is the base case solve it then substitute back all the variables accordingly.
jz/
Now back substitution
xi- 2c* /
bb* yc * - 2c* /
bb* 4a* c * -2a*/
The Manual conversion is correct because when we reverse the infix expression to calculate the prefix, the associativity of the expression changes from left to right to right to left which is not considered in the algorithm and often it is ignored.
Example:
expression:5-3-2 :infix to prefix(manual conversion)
(-5 3)-2
-(- 5 3) 2
- - 5 3 2
now by the algorithm(if associativity not changed)
reverse expression: 2 - 3 - 5
postfix: 2 3 - 5 -
again reverse to get prefix: - 5 - 3 2
now see if we ignored the associativity, it made a huge difference
now if we change the associativity from left to right to right to left:
then :
reverse expression: 2 - 3 - 5
postfix: 2 3 5 - - (like a^b^b to postfix: abc^^ because it is also right associative)
reverse - - 5 3 2
I know that modulus gives the remainder and that this code will give the survivor of the Josephus Problem. I have noticed a pattern that when n mod k = 0, the starting count point begins at the very beginning of the circle and that when n mod k = 1, the person immediately before the beginning of the circle survived that execution round through the circle.
I just don't understand how this recursion uses modulus to find the last man standing and what josephus(n-1,k) is actually referring to. Is it referring to the last person to get executed or the last survivor of a specific round through the circle?
def josephus( n, k):
if n ==1:
return 1
else:
return ((josephus(n-1,k)+k-1) % n)+1
This answer is both a summary of the Josephus Problem and an answer to your questions of:
What is josephus(n-1,k) referring to?
What is the modulus operator being used for?
When calling josephus(n-1,k) that means that you've executed every kth person up to a total of n-1 times. (Changed to match George Tomlinson's comment)
The recursion keeps going until there is 1 person standing, and when the function returns itself to the top, it will return the position that you will have to be in to survive. The modulus operator is being used to help stay within the circle (just as GuyGreer explained in the comments). Here is a picture to help explain:
1 2
6 3
5 4
Let the n = 6 and k = 2 (execute every 2nd person in the circle). First run through the function once and you have executed the 2nd person, the circle becomes:
1 X
6 3
5 4
Continue through the recursion until the last person remains will result in the following sequence:
1 2 1 X 1 X 1 X 1 X X X
6 3 -> 6 3 -> 6 3 -> X 3 -> X X -> X X
5 4 5 4 5 X 5 X 5 X 5 X
When we check the values returned from josephus at n we get the following values:
n = 1 return 1
n = 2 return (1 + 2 - 1) % 2 + 1 = 1
n = 3 return (1 + 2 - 1) % 3 + 1 = 3
n = 4 return (3 + 2 - 1) % 4 + 1 = 1
n = 5 return (1 + 2 - 1) % 5 + 1 = 3
n = 6 return (3 + 2 - 1) % 6 + 1 = 5
Which shows that josephus(n-1,k) refers to the position of the last survivor. (1)
If we removed the modulus operator then you will see that this will return the 11th position but there is only 6 here so the modulus operator helps keep the counting within the bounds of the circle. (2)
Your first question has been answered above in the comments.
To answer your second question, it's referring to the position of the last survivor.
Consider j(4,2).
Using the algorithm gives
j(4,2)=(j(3,2)+1)%4)+1
j(3,2)=(j(2,2)+1)%3)+1
j(2,2)=(j(1,2)+1)%2)+1
j(1,2)=1
and so
j(2,2)=((1+1)%2)+1=1
j(3,2)=((1+1)%3)+1=3
j(4,2)=((3+1)%4)+1=1
Now the table of j(2,2) is
1 2
1 x
so j(2,2) is indeed 1.
For j(3,2) we have
1 2 3
1 x 3
x x 3
so j(3,2) is 3 as required.
Finally, j(4,2) is
1 2 3 4
1 x 3 4
1 x 3 x
1 x x x
which tells us that j(4,2)=1 as required.
I want to create a BST from a sorted linked list. I have solved the problem for recursively but was wondering how to write an iterative solution for the same without changing the complexity of the problem.
[EDIT]
Note: I do not want to implement my own stack.
[EDIT2]
The function that recursively calls itself be f. Pseudo code is given below. Call f with head pointer from main
node * f(int start_index, int end_index, node *ptr) {
if ( start>end) return NULL
middle_index = start_index + (end_index-start_index)/2
node *l_child = f(start_index, middle_index-1, ptr)
initialize parent with ptr's value
parent->left = l_child
ptr = ptr->next
parent->right = f(middle_index+1, end, ptr)
return parent
}
Assuming ahead of time that you want it to be like so, roughly:
_______
/ \
/ \ / \
/ \ / \
/ \ / \ / \ /
1 2 3 4 5 6 7
then you can explicitly solve for the structure. In this case, for a list of length L<2N for some integer N, and assuming you create all nodes and leave some leaves as "null" (or alternatively don't even construct those nodes), you have the total number of nodes in the tree equal to (2*2N)-1. Your nodes would look like:
12345678
/ \
1234 5678
/ \ / \
12 34 56 78
/ \ / \ / \ / \
1 2 3 4 5 6 7
I mentioned the size of the nodes because it should give us insight into how to proceed: there ought to be some way to enumerate {1,2}->12, {3,4}->34, {12,34}->1234, .... One way to proceed is to start grouping nodes from the bottom. For example, we could do this in N (3) passes:
step 1: 1 2 3 4 5 6 7
step 2: (1 2) (3 4) (5 6) (7 )
step 3: ((1 2) (3 4))((5 6) (7 ))
step 4: (((1 2) (3 4))((5 6) (7 )))
Another alternative is to use a stack to keep track of the higher level nodes as we group them.
Another way is to create an explicit formula for the structure. We create 7 nodes and set their children as follows: {1,2}, {3,4}, {5,6}, {7,null}, {12,34}, {56,78}, {1234,5678}. In particular if we index the nodes in a linear scheme, this pattern would be: 9={1,2}, 10={3,4}, 11={5,6}, 12={7,null}, 13={9,10}, 14={11,12}, 15={13,14}. Simply incrementing appears to give the exact pattern of a balanced binary tree. This will use no additional memory.
You can convert any recursive solution to an "iterative" solution by simulating a stack.
I've been looking at the wiki page: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
I've used the code example to build the first part, basically I can currently turn :
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 into 3 4 2 * 1 5 − 2 3 ^ ^ / +
But I don't know how to then use 3 4 2 * 1 5 − 2 3 ^ ^ / + to obtain 3.00012207
And the example code and explanation on wiki aren't making any sense to me.
Could someone please explain how to evaluate 3 4 2 * 1 5 − 2 3 ^ ^ / + and produce the answer. Thanks in advance. I don't need a code example just a good explanation or a breakdown of an example.
Not that it matters but I am working .net C#.
The purpose of the shunting yard algorithm is that its output is in Reverse Polish Notation, which is straightforward to evaluate:
create a stack to hold values
while there is reverse polish notation input left:
read an item of input
if it is a value, push it onto the stack
otherwise, it is an operation; pop values from the stack, perform the operation on those values, push the result back
when there's no input left, if the expression was well formed, there should be exactly one value on the stack; this is the evaluated result.
The post-fix notation is how you do the math in, say, a HP calculator.
Keep a stack, whenever you get a number add it to the top. Whenever you get an operator consume inputs from the top and then add the result to the top
token stack
*empty*
3 3 //push numbers...
4 3 4
2 3 4 2
* 3 8 //remove 4 and 2, add 4*2=8
1 3 8 1
5 3 8 1 5
- 3 8 -4
2 3 8 -4 2
3 3 8 -4 2 3
^ 3 8 -4 8
... ...
Process the elements 3 4 2 * 1 5 − 2 3 ^ ^ / + left-to-right as follows:
Initialize a stack to hold numbers.
If the element is a number, push it onto the stack.
if the element is an operator, remove the top two elements from the stack, apply the operator to those two elements, and push the result onto the stack.
When you get to the end, the stack should have a single element which will be the result.
I see I am a bit late to the party.
I saw the question and went off on a tangent writing a couple of tasks for Rosetta Code. It just so happens that this task might be what you are after. It gives an annottated table of what happens when calculating the value of an RPN expression, token by token.
Here is a sample of its output:
For RPN expression: '3 4 2 * 1 5 - 2 3 ^ ^ / +'
TOKEN ACTION STACK
3 Push num onto top of stack 3
4 Push num onto top of stack 3 4
2 Push num onto top of stack 3 4 2
* Apply op to top of stack 3 8
1 Push num onto top of stack 3 8 1
5 Push num onto top of stack 3 8 1 5
- Apply op to top of stack 3 8 -4
2 Push num onto top of stack 3 8 -4 2
3 Push num onto top of stack 3 8 -4 2 3
^ Apply op to top of stack 3 8 -4 8
^ Apply op to top of stack 3 8 65536
/ Apply op to top of stack 3 0.0001220703125
+ Apply op to top of stack 3.0001220703125
The final output value is: '3.0001220703125'