Created
December 13, 2017 12:15
-
-
Save mastro35/323ff290df90bcca36a1b0fb5720d694 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 = [] | |
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): | |
op2 = self.stack.pop() | |
op1 = self.stack.pop() | |
self.push(op1 + op2) | |
def subtract_two_numbers(self): | |
op2 = self.stack.pop() | |
op1 = self.stack.pop() | |
self.push(op1 - op2) | |
def multiply_two_numbers(self): | |
op2 = self.stack.pop() | |
op1 = self.stack.pop() | |
self.push(op1 * op2) | |
def divide_two_numbers(self): | |
op2 = self.stack.pop() | |
op1 = self.stack.pop() | |
self.push(op1 / op2) | |
def pow2_a_number(self): | |
op1 = self.stack.pop() | |
self.push(op1 * op1) | |
def sqrt_a_number(self): | |
op1 = self.stack.pop() | |
self.push(math.sqrt(op1)) | |
def compute(self, operation): | |
""" compute an operation """ | |
if operation == '+': | |
self.sum_two_numbers() | |
if operation == '-': | |
self.subtract_two_numbers() | |
if operation == '*': | |
self.multiply_two_numbers() | |
if operation == '/': | |
self.divide_two_numbers() | |
if operation == '^2': | |
self.pow2_a_number() | |
if operation == 'SQRT': | |
self.sqrt_a_number() | |
if operation == 'C': | |
self.stack.pop() | |
if operation == 'AC': | |
self.stack.clear() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment