How to evaluate the following prefix expression?

1.4k Views Asked by At

Can you please help in evaluating following prefix expression? Thank you.

– ^ / + + 4 6 2 – 4 1 2 9

2

There are 2 best solutions below

1
On

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 9 in 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.

  1. Token = 9, append to list, list = [9]
  2. Token = 2, append to list, list = [9, 2]
  3. Token = 1, append to list, list = [9, 2, 1]
  4. Token = 4, append to list, list = [9, 2, 1, 4]
  5. Token = -, calculate result using $4$ and $1$, giving us $4 - 1 = 3$, and we append 3: list = [9, 2, 3]
  6. Token = 2, append to list, list = [9, 2, 3, 2]
  7. Token = 6, append to list, list = [9, 2, 3, 2, 6]
  8. Token = 4, append to list, list = [9, 2, 3, 2, 6, 4]
  9. Token = +, calculate 6 + 4, list = [9, 2, 3, 2, 10]
  10. Token = +, calculate 2 + 10, list = [9, 2, 3, 12]
  11. Token = /, calculate 12 / 3, list = [9, 2, 4]
  12. Token = ^, calculate 4 ^ 2, list = [9, 16]
  13. Token = -, calculate 16 - 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.

0
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.