No.2 Calculatior
1 import re 2 class Calculator(): 3 ''' 4 Calculator 5 ''' 6 def run(self, equation): 7 ''' 8 main 9 ''' 10 equation = equation.replace(' ','') 11 while True: 12 result = re.search('\([^(^)]+\)', equation) 13 if result: 14 equation_min = self.Equation_dispose(result.group()) 15 value = str(self.A_S(equation_min)) 16 equation = equation.replace(result.group(), value) 17 equation = self.format(equation) 18 else:break 19 equation = self.format(equation) 20 sum = self.A_S(self.Equation_dispose(equation)) 21 print(sum) 22 23 def M_D(self, equation): 24 ''' 25 multiply-divide 26 ''' 27 equation = equation.replace(' ','') 28 if "*" in equation: 29 a,b = equation.split('*') 30 return str(float(a) * float(b)) 31 if "/" in equation: 32 a,b = equation.split('/') 33 return str(float(a) / float(b)) 34 35 def A_S(self, equation): 36 ''' 37 add-sub 38 ''' 39 # equation 40 ret = re.findall('[+-]?\d+(?:\.\d+)?', equation) 41 sum = 0 42 for x in ret: 43 sum += float(x) 44 return sum 45 46 def Equation_dispose(self, equation): 47 ''' 48 Equation-format 49 ''' 50 while True: 51 result1 = re.search('\d+(\.\d+)?[*/]\d+(\.\d+)?', equation) 52 if result1: 53 result1 = result1.group() 54 result2 = self.M_D(result1) 55 equation = equation.replace(result1, result2) 56 else:return equation 57 58 def format(self, equation): 59 equation = equation.replace('+-', '-') 60 equation = equation.replace('--', '+') 61 equation = equation.replace('-+', '-') 62 equation = equation.replace('++', '+') 63 return equation 64 65 equation = input("") 66 calculator = Calculator() 67 calculator.run(equation)