Advertisement
differen71

BulkCalculator

Jun 9th, 2023
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. import re
  2. from _collections import deque
  3.  
  4. # BULK CALCULATOR APP
  5. # Calculates a single line of values given as a single string e.g. "£10 + £10 - £10 * 0.5"
  6.  
  7. class Calculator:
  8.     def __init__(self, data: str):
  9.         self.data = data
  10.  
  11.     @staticmethod
  12.     def add(value1, value2):
  13.         result = value1 + value2
  14.         return result
  15.  
  16.     @staticmethod
  17.     def subtract(value1, value2):
  18.         result = value1 - value2
  19.         return result
  20.  
  21.     @staticmethod
  22.     def multiply(value1, value2):
  23.         result = value1 * value2
  24.         return result
  25.  
  26.     @staticmethod
  27.     def divide(value1, value2):
  28.         try:
  29.             result = value1 / value2
  30.         except ZeroDivisionError:
  31.             return 'Cannot divide to 0.'
  32.         return result
  33.  
  34.     def analysing_data(self):
  35.         data = deque()
  36.         pattern = r"((-?(?:\d+(?:\.\d+)?))|([-+\/*()])|(-?\.\d+))"
  37.         result = re.finditer(pattern, self.data)
  38.  
  39.         for element in result:
  40.             data.append(element.group())
  41.  
  42.         return data
  43.  
  44.     def calculating(self):
  45.         data = self.analysing_data()
  46.         result = float(data.popleft())
  47.  
  48.         while data:
  49.             current_operator = data.popleft()
  50.             value = float(data.popleft())
  51.  
  52.             operations_map = {
  53.                 '+': self.add(result, value),
  54.                 '-': self.subtract(result, value),
  55.                 '*': self.multiply(result, value),
  56.                 '/': self.divide(result, value),
  57.             }
  58.  
  59.             result = operations_map[current_operator]
  60.  
  61.         return f"{result:.2f}"
  62.  
  63.  
  64. app = Calculator('20 + 100 - 10 - 100')
  65. print(app.calculating())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement