Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
"""
Engine class of the RPN Calculator
"""
import math
from inspect import signature
class rpn_engine:
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 {"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y,
"^2": lambda x: x * x,
"SQRT": lambda x: math.sqrt(x),
"C": lambda: self.stack.pop(),
"AC": 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 """
function_requested = self.catalog[operation]
number_of_operands = 0
function_signature = signature(function_requested)
number_of_operands = len(function_signature.parameters)
if number_of_operands == 2:
self.compute_operation_with_two_operands(self.catalog[operation])
if number_of_operands == 1:
self.compute_operation_with_one_operand(self.catalog[operation])
if number_of_operands == 0:
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
You can’t perform that action at this time.