Search code examples
pythonmathnotationaddition

prefix notation parsing in python


Right off the bat - no, this is NOT homework.

I would like to write a prefix notation parser in python (for sums presently)... for example

if given: + 2 2 it would return: 4

ideas?


Solution

  • def prefix(input):
      op, num1, num2 = input.split(" ")
      num1 = int(num1)
      num2 = int(num2)
      if op == "+":
        return num1 + num2
      elif op == "*":
        return num1 * num2
      else:
        # handle invalid op
        return 0
    
    print prefix("+ 2 2")
    

    prints 4, also included a multiplication operator just to show how to expand it.