Guest User

RPNCalculator

a guest
Jun 16th, 2018
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. """
  2. Engine class of the RPN Calculator
  3. """
  4.  
  5. import math
  6.  
  7.  
  8. class RPNEngine:
  9.   def __init__(self):
  10.     """ Constructor """
  11.     self.stack = []
  12.     self.catalog = self.get_functions_catalog()
  13.  
  14.   def get_functions_catalog(self):
  15.     """ Returns the catalog of all the functions supported by the calculator """
  16.     return {"+": (2, lambda x, y: x + y),
  17.             "-": (2, lambda x, y: x - y),
  18.             "*": (2, lambda x, y: x * y),
  19.             "/": (2, lambda x, y: x / y),
  20.             "^2": (1, lambda x: x * x),
  21.             "SQRT": (1, math.sqrt),
  22.             "C": (0, lambda: self.stack.pop()),
  23.             "AC": (0, lambda: self.stack.clear())}
  24.  
  25.   def push(self, number):
  26.     """ push a value to the internal stack """
  27.     self.stack.append(number)
  28.  
  29.   def pop(self):
  30.     """ pop a value from the stack """
  31.     try:
  32.       return self.stack.pop()
  33.     except IndexError:
  34.       pass  # do not notify any error if the stack is empty...
  35.  
  36.   def compute(self, operation):
  37.     """ compute an operation """
  38.     op_arity, op_func = self.catalog[operation]
  39.  
  40.     if len(self.stack) >= op_arity:
  41.       op_args = []
  42.       for _ in range(op_arity):
  43.         op_args.insert(0, self.stack.pop())  # Insert at front to preserve stack order
  44.       result = op_func(*op_args)
  45.       self.push(result)
  46.     else:
  47.       print("Not enough operands on the stack")
Advertisement
Add Comment
Please, Sign In to add comment