1
$\begingroup$

So the question is to convert the following expression to postfix:

(a+b)^(p+q)^(r*s*t)

The answer I get when I calculate is: ab+pq+^rs*t*^

But the answer is given to be ab+pq+rs*t*^^

I assume that the step when you need to push second '^' into stack when there is already a '^' in the stack is where I went wrong (I pop out the '^' before pushing). Shouldn't we pop out the first '^' as they are of equal precedence ? Or is it an exception to '^' operator ?

$\endgroup$
  • $\begingroup$ Welcome to Computer Science! The critical information is what is your "^" operator. Does it mean bit-xor or raising to a power? It would be nice to provide a url or reference to tell us the context. $\endgroup$ – Apass.Jack Nov 3 '18 at 17:52
  • $\begingroup$ Thanks! It is an exponent operator. And regarding the reference, it was a question in a small online quiz related to stacks. $\endgroup$ – Debasish Das Nov 3 '18 at 19:02
0
$\begingroup$

There is a sort of an exception to '^', the exponentiation operator since it is right associative. That is, $a^{b^c}$ means $a^{\left({b^c}\right)}$ instead of $\left(a^b\right)^c$. That is, (a+b)^(p+q)^(r*s*t) means (a+b)^((p+q)^(r*s*t)) instead of ((a+b)^(p+q))^(r*s*t).

When you reach the first ^ while evaluating postfix expression ab+pq+rs*t*^^, you will pop out the result of rs*t* and the result of pq+. You get the expected exponentiation as expected.

$\endgroup$
  • $\begingroup$ The use of extra brackets made it all clear. Thanks a lot ! $\endgroup$ – Debasish Das Nov 6 '18 at 10:22
  • $\begingroup$ You are welcome! Please consider accepting my answer. (Thanks in word without upvote or acceptance is more like the antithesis of thanks on StackExchange.) $\endgroup$ – Apass.Jack Nov 10 '18 at 16:49
  • $\begingroup$ I actually upvoted (since I have less than 15 reputation, it doesn't show up) $\endgroup$ – Debasish Das Nov 11 '18 at 17:03
  • $\begingroup$ I see. I just upvoted this nice question of yours so that you are nearer to the privilege of upvoting. $\endgroup$ – Apass.Jack Nov 11 '18 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.