Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Engine class of the RPN Calculator
- """
- import math
- class RPNEngine:
- def __init__(self):
- """ Constructor """
- self.stack = []
- self.catalog = self.get_functions_catalog()
- def get_functions_catalog(self):
- """ Returns the catalog of all the functions supported by the calculator """
- return {"+": (2, lambda x, y: x + y),
- "-": (2, lambda x, y: x - y),
- "*": (2, lambda x, y: x * y),
- "/": (2, lambda x, y: x / y),
- "^2": (1, lambda x: x * x),
- "SQRT": (1, math.sqrt),
- "C": (0, lambda: self.stack.pop()),
- "AC": (0, lambda: self.stack.clear())}
- def push(self, number):
- """ push a value to the internal stack """
- self.stack.append(number)
- def pop(self):
- """ pop a value from the stack """
- try:
- return self.stack.pop()
- except IndexError:
- pass # do not notify any error if the stack is empty...
- def compute(self, operation):
- """ compute an operation """
- op_arity, op_func = self.catalog[operation]
- if len(self.stack) >= op_arity:
- op_args = []
- for _ in range(op_arity):
- op_args.insert(0, self.stack.pop()) # Insert at front to preserve stack order
- result = op_func(*op_args)
- self.push(result)
- else:
- print("Not enough operands on the stack")
Advertisement
Add Comment
Please, Sign In to add comment