Skip to content

Instantly share code, notes, and snippets.

@mastro35
Created December 13, 2017 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mastro35/20169a158b32c0cdfc835cf8e980162c to your computer and use it in GitHub Desktop.
Save mastro35/20169a158b32c0cdfc835cf8e980162c to your computer and use it in GitHub Desktop.
"""
Engine class of the RPN Calculator
"""
import math
class rpn_engine:
def __init__(self):
""" Constructor """
self.stack = []
self.catalog = self.get_functions_catalog()
def get_functions_catalog(self):
return {"+": self.sum_two_numbers,
"-": self.subtract_two_numbers,
"*": self.multiply_two_numbers,
"/": self.divide_two_numbers,
"^2": self.pow2_a_number,
"SQRT": self.sqrt_a_number,
"C": self.stack.pop,
"AC": 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 sum_two_numbers(self, op1, op2):
return op1 + op2
def subtract_two_numbers(self, op1, op2):
return op1 - op2
def multiply_two_numbers(self, op1, op2):
return op1 * op2
def divide_two_numbers(self, op1, op2):
return op1 / op2
def pow2_a_number(self, op1):
return op1 * op1
def sqrt_a_number(self, op1):
return math.sqrt(op1)
def compute(self, operation):
""" compute an operation """
if operation in ['+', '-', '*', '/']:
self.compute_operation_with_two_operands(self.catalog[operation])
if operation in ['^2', 'SQRT']:
self.compute_operation_with_one_operand(self.catalog[operation])
if operation in ['C', 'AC']:
self.compute_operation_with_no_operands(self.catalog[operation])
def compute_operation_with_two_operands(self, operation):
""" exec operations with two operands """
try:
if len(self.stack) < 2:
raise BaseException("Not enough operands on the stack")
op2 = self.stack.pop()
op1 = self.stack.pop()
result = operation(op1, op2)
self.push(result)
except BaseException as error:
print(error)
def compute_operation_with_one_operand(self, operation):
""" exec operations with one operand """
try:
op1 = self.stack.pop()
result = operation(op1)
self.push(result)
except BaseException as error:
print(error)
def compute_operation_with_no_operands(self, operation):
""" exec operations with no operands """
try:
operation()
except BaseException as error:
print(error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment