Created
December 13, 2017 12:28
-
-
Save mastro35/e2d4821ad89164d2431b4efb4d1084b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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 {"+": 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": 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 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