0

How to calculate the value of post fix notation: i tried with:

import operator

operator = {
    '+': operator.add, '-':  operator.sub,
    '*': operator.mul, '/':  operator.div, '%':  operator.mod,
    '**': operator.pow, '//': operator.floordiv,
}
l = []
exp = "11+2*"
for i in exp:
    if i in operator:
        a = operator[i]
        x = l[0]
        y = l[1]
        l[-2:] = [a(*l[-2:])]
        print l
    else:
        l.append(i)
        print l

How to do this?

Surya Gupta
  • 165
  • 6
  • 13
  • http://stackoverflow.com/questions/3865939/can-this-python-postfix-notation-reverse-polish-notation-interpreter-be-made-m – Jared Mar 20 '13 at 06:30

2 Answers2

0

Make sure to have Python parse your characters into integers before adding them to the stack:

l.append(int(i))
Ric
  • 8,615
  • 3
  • 17
  • 21
0

Some hints:

  • You need a better parser, iterating just character by character will not be enough (unless you only want to have single digit numbers). To make it a little simpler, you could require that numbers and operators are delimited by whitespace each and use str.split:

    elems = "11 2 3 + *".split()
    
  • You need to convert the numbers to integers before pushing them on the stack

The stack operation also looks a little weird. Having it as

l.append(a(l.pop(), l.pop())

makes it more explicit.

Torsten Marek
  • 83,780
  • 21
  • 91
  • 98