Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- from _collections import deque
- # BULK CALCULATOR APP
- # Calculates a single line of values given as a single string e.g. "£10 + £10 - £10 * 0.5"
- class Calculator:
- def __init__(self, data: str):
- self.data = data
- @staticmethod
- def add(value1, value2):
- result = value1 + value2
- return result
- @staticmethod
- def subtract(value1, value2):
- result = value1 - value2
- return result
- @staticmethod
- def multiply(value1, value2):
- result = value1 * value2
- return result
- @staticmethod
- def divide(value1, value2):
- try:
- result = value1 / value2
- except ZeroDivisionError:
- return 'Cannot divide to 0.'
- return result
- def analysing_data(self):
- data = deque()
- pattern = r"((-?(?:\d+(?:\.\d+)?))|([-+\/*()])|(-?\.\d+))"
- result = re.finditer(pattern, self.data)
- for element in result:
- data.append(element.group())
- return data
- def calculating(self):
- data = self.analysing_data()
- result = float(data.popleft())
- while data:
- current_operator = data.popleft()
- value = float(data.popleft())
- operations_map = {
- '+': self.add(result, value),
- '-': self.subtract(result, value),
- '*': self.multiply(result, value),
- '/': self.divide(result, value),
- }
- result = operations_map[current_operator]
- return f"{result:.2f}"
- app = Calculator('20 + 100 - 10 - 100')
- print(app.calculating())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement