|
Someone replied with and then unfortunately deleted an extremely good suggestion. Instead of each operation taking a variable number of numbers and then either returning a value or directly changing the state of the stack (which was also a bug in my previous gist, in pushing the result of C and AC): homogenize the types of the operations by making all of them take a stack and return a stack. You could also wrap all of the basic arithmetic functions with a higher-level function so that, eg, `add` would still not actually have to be aware of the stack: import math, operator
def stackFunction(arity, function):
return lambda stack: stack[:-arity] + [function(*stack[-arity:])]
class rpn_engine:
def __init__(self):
self.stack = []
self.catalog = {"+": stackFunction(2, operator.add),
"-": stackFunction(2, operator.sub),
"*": stackFunction(2, operator.mul),
"/": stackFunction(2, operator.truediv),
"^2": stackFunction(1, lambda x: x * x),
"SQRT": stackFunction(1, math.sqrt),
"C": lambda stack: stack[:-1],
"AC": lambda stack: []}
def compute(self, operation):
self.stack = self.catalog[operation](self.stack)
def push(self, number):
self.stack.append(number)
|