I am having problems with my reverse polish calculator code. The code is as follows:
import operator
OPERATORS = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.div,
}
class Stack(object):
"Creates a stack to enter numbers or operators into"
def __init__(self):
self.storage = [0,0,0,0]
self.sptn = -1
def push(self, item):
self.sptn = self.sptn + 1
self.storage[self.sptn] = item
def pop(self):
self.sptn = self.sptn -1
def top(self):
return self.storage[self.sptn]
def __rep__(self):
return self.storage[:self.sptn + 1]
def get_input():
equation = raw_input("Enter the equation in reverse polish notation: ")
return equation
def evaluate_rpn(equation):
s = Stack()
try:
for item in equation.split():
try:
result = float(item)
s.push(result)
except ValueError:
x = s.pop()
y = s.pop()
result = OPERATORS[item](x, y)
s.push(result)
result = s.top()
except IndexError:
print "Please input at least two numbers before entering an operator."
def main():
equation = get_input()
answer = evaluate_rpn(raw_input("Enter the equation in reverse polish notation: "))
print answer
The code trips up when it hits an operator for some reason. The line is causing me trouble is the "results = OPERATOR[item] (x, y)"
I would appreaciate any help!!! Please!!!
Thanks