Guest User

Untitled

a guest
Dec 15th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. """
  2. Engine class of the RPN Calculator
  3. """
  4.  
  5. import math
  6.  
  7. class rpn_engine:
  8. def __init__(self):
  9. """ Constructor """
  10. self.stack = []
  11. self.catalog = self.get_functions_catalog()
  12.  
  13. def get_functions_catalog(self):
  14. return {"+": self.sum_two_numbers,
  15. "-": self.subtract_two_numbers,
  16. "*": self.multiply_two_numbers,
  17. "/": self.divide_two_numbers,
  18. "^2": self.pow2_a_number,
  19. "SQRT": self.sqrt_a_number,
  20. "C": self.stack.pop,
  21. "AC": self.stack.clear}
  22.  
  23. def push(self, number):
  24. """ push a value to the internal stack """
  25. self.stack.append(number)
  26.  
  27. def pop(self):
  28. """ pop a value from the stack """
  29. try:
  30. return self.stack.pop()
  31. except IndexError:
  32. pass # do not notify any error if the stack is empty...
  33.  
  34. def sum_two_numbers(self, op1, op2):
  35. return op1 + op2
  36.  
  37. def subtract_two_numbers(self, op1, op2):
  38. return op1 - op2
  39.  
  40. def multiply_two_numbers(self, op1, op2):
  41. return op1 * op2
  42.  
  43. def divide_two_numbers(self, op1, op2):
  44. return op1 / op2
  45.  
  46. def pow2_a_number(self, op1):
  47. return op1 * op1
  48.  
  49. def sqrt_a_number(self, op1):
  50. return math.sqrt(op1)
  51.  
  52.  
  53. def compute(self, operation):
  54. """ compute an operation """
  55.  
  56. if operation in ['+', '-', '*', '/']:
  57. self.compute_operation_with_two_operands(self.catalog[operation])
  58.  
  59. if operation in ['^2', 'SQRT']:
  60. self.compute_operation_with_one_operand(self.catalog[operation])
  61.  
  62. if operation in ['C', 'AC']:
  63. self.compute_operation_with_no_operands(self.catalog[operation])
  64.  
  65. def compute_operation_with_two_operands(self, operation):
  66. """ exec operations with two operands """
  67. try:
  68. if len(self.stack) < 2:
  69. raise BaseException("Not enough operands on the stack")
  70.  
  71. op2 = self.stack.pop()
  72. op1 = self.stack.pop()
  73. result = operation(op1, op2)
  74. self.push(result)
  75. except BaseException as error:
  76. print(error)
  77.  
  78. def compute_operation_with_one_operand(self, operation):
  79. """ exec operations with one operand """
  80. try:
  81. op1 = self.stack.pop()
  82. result = operation(op1)
  83. self.push(result)
  84. except BaseException as error:
  85. print(error)
  86.  
  87. def compute_operation_with_no_operands(self, operation):
  88. """ exec operations with no operands """
  89. try:
  90. operation()
  91. except BaseException as error:
  92. print(error)
Add Comment
Please, Sign In to add comment