1
$\begingroup$

I am somewhat stuck in converting an expression with negative numbers from infix to postfix.

Suppose we have a expression like

a = -b - (-c - d) .

At some places I read that you can parathesize the negative numbers to solve the problem. But if I parathesize them as

a = (-b) - ((-c) - d), then at the beginning of the postfix expression I would get "ab-" which means a-b and is incorrect.

Can someone help me?

$\endgroup$
3
  • $\begingroup$ Usually we convert expressions, not assignment statements like $a= -b + 4 - x \dots$. What do you want to convert? $\endgroup$
    – fade2black
    Commented Oct 22, 2017 at 19:11
  • $\begingroup$ @fade2black I want to convert the entire statement including assignment. Because that 'a' before the assignment is causing problem for me. $\endgroup$
    – Zephyr
    Commented Oct 22, 2017 at 19:12
  • 1
    $\begingroup$ You could also read this post. I provide Ruby code that converts infix expressions into postfix. $\endgroup$
    – fade2black
    Commented Oct 22, 2017 at 19:43

1 Answer 1

1
$\begingroup$

Canonically, we convert from infix to postfix form only expressions. However, you can enhance this by introducing the assignment operator = in addition to the standard four binary operators +, -, *, and /. Just define the conversion as: a = b becomes ab=. So for example, a = x + 5 becomes ax5+=.

As for the negative numbers, you can parenthesize them (as you suggest). For example, a = -b + 2 becomes a(-b)2+= or just separate each operand or operator by a single space, for example the previous postfix expression can be written as a -b 2 + =. This is another example: derv = -dy/dx + 5*(-x) becomes derv(-dy)dx/5(-x)*+= or derv -dy dx / 5 -x * + =.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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