Guest User

Untitled

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