RPN to infix with both numbers and pronumerals in Python

120 Views Asked by At

I am making a Python program where I get an RPN expression separated by spaces and convert it to infix. It should work like this:

Input RPN: x 2 ^ 3 - 1 2 x * - *

Output : -2x^3 + x^2 + 6x - 3

However, I cannot get it to work with both pronumerals and numbers, for example multiplying it by the pronumeral and again multiplying the entire thing.

Here is my code to compute RPN so far:

def getInfix(exp) :
  stack = []
  for i in exp.split(' '):
    if not i in "+-*^" or i.isdigit():
      stack.append(i)
    else:
      stack_one = stack[0]
      stack.pop(0)
      stack_two = stack[0]
      stack.pop(0)
      if str(stack_one).isdigit() and str(stack_two).isdigit():
        stack.insert(0, stack_one + stack_two)
      else:
        stack.insert(0, stack_one + i + stack_two)
      
  return ''.join(stack)

if __name__ == '__main__':
  exp = "x 2 ^ 3 - 1 2 x * - *"
  print(getInfix(exp.strip()))

When inputted: x 2 ^ 3 - 1 2 x * - *

Into the exp variable in the main function,

It outputs this: x^2-3 * 1-2 * x

When it should be outputting this: -2x^3 + x^2 + 6x - 3

Where am I going wrong with my code? I have tried doing the same thing with just pronumerals and just numbers and it seems to work...

For reference, I am following the RPN (Shunting Yard) algorithm:

https://en.wikipedia.org/wiki/Reverse_Polish_notation

https://en.wikipedia.org/wiki/Shunting_yard_algorithm

0

There are 0 best solutions below