Can you please help in evaluating following prefix expression? Thank you.
– ^ / + + 4 6 2 – 4 1 2 9
Can you please help in evaluating following prefix expression? Thank you.
– ^ / + + 4 6 2 – 4 1 2 9
On
I put in brackets everywhere first, starting with each operation and enclosing two arguments
– ^ / + + 4 6 2 – 4 1 2 9
= (– (^ (/ (+ (+ 4 6) 2) (– 4 1)) 2) 9)
Generally the arguments are single digit numbers, apart from where the minus sign appears; in this case the result of the minus operation is an argument.
Hopefully from here it should be straight-forward to see what to do. One way would be to convert everything into infix notation;
(– (^ (/ (+ (+ 4 6) 2) (– 4 1)) 2) 9)
= (((4+6)+2)/(4-1))^2 - 9
= 7
Or you could go through and evaluate the prefix operations one by one, like Gareth Ma's answer.
The standard way to evaluate prefix expression is a stack. If you have not heard of it before, it is easy to understand anyways, as I will show.
We will process your expression
– ^ / + + 4 6 2 – 4 1 2 9in reverse order, while maintaining a list of numbers. Every time we see a number, we append it to the end of the list. If we see an operand (+ - * / ^), we will calculate the result using the last two numbers in our list, remove the two numbers, and append the result instead.Below, I will process each token of your expression one by one, while keeping track of the list.
9, append to list, list =[9]2, append to list, list =[9, 2]1, append to list, list =[9, 2, 1]4, append to list, list =[9, 2, 1, 4]-, calculate result using $4$ and $1$, giving us $4 - 1 = 3$, and we append 3: list =[9, 2, 3]2, append to list, list =[9, 2, 3, 2]6, append to list, list =[9, 2, 3, 2, 6]4, append to list, list =[9, 2, 3, 2, 6, 4]+, calculate6 + 4, list =[9, 2, 3, 2, 10]+, calculate2 + 10, list =[9, 2, 3, 12]/, calculate12 / 3, list =[9, 2, 4]^, calculate4 ^ 2, list =[9, 16]-, calculate16 - 9, list =[7]As you can see, the result is
7. If at any point the list is empty (i.e. "adding one number"), then the expression is invalid.Hope this helps.