python实现最简单的计算器功能源码
1 import re 2 3 4 def calc(formula): 5 formula = re.sub(' ', '', formula) 6 formula_ret = 0 7 match_brackets = re.search(r'\([^()]+\)', formula) 8 if match_brackets: 9 calc_result = calc(match_brackets.group().strip("(,)")) 10 formula = formula.replace(match_brackets.group(), str(calc_result)) 11 return calc(formula) 12 else: 13 formula = formula.replace('--', '+').replace('++', '+').replace('-+', '-').replace('+-', '-') 14 while re.findall(r"[*/]", formula): 15 get_formula = re.search(r"[.\d]+[*/]+[-]?[.\d]+", formula) 16 if get_formula: 17 get_formula_str = get_formula.group() 18 if get_formula_str.count("*"): 19 formula_list = get_formula_str.split("*") 20 ret = float(formula_list[0]) * float(formula_list[1]) 21 else: 22 formula_list = get_formula_str.split("/") 23 ret = float(formula_list[0]) / float(formula_list[1]) 24 formula = formula.replace(get_formula_str, str(ret)).replace('--', '+').replace('++', '+') 25 formula = re.findall(r'[-]?[.\d]+', formula) 26 for num in formula: 27 formula_ret += float(num) 28 return formula_ret 29 # calc_str = input('>>>') 30 calc_str = '1-2*((60-30+(-40---5)*(9-2*5/3+7/3*99/4*2998+ 10*568/ 14))-(-4*3)/(16-3*2))' 31 print(eval(calc_str)) 32 formula_result = calc(calc_str) 33 print(formula_result)
带基本验证
1 import re 2 invalid_str_re = re.compile(r'[*/]{3,}|[%]{2,}|\([*/%]+\d+|^[*/%]+\d+|\(+\)+|\d+[-+*/%]+$|\)+\(+|\d+[-+*/%]+\)|\d+\(+') 3 4 5 def decorate(func): 6 def wrapper(formula): 7 formula = re.sub(' ', '', formula) 8 valid_str = re.findall(r'[-+*/%.()\d]+', formula) 9 invalid_str = invalid_str_re.findall(formula) 10 if (valid_str and len(valid_str[0]) != len(formula)) or invalid_str: 11 return False 12 return func(formula) 13 return wrapper 14 15 16 @decorate 17 def calc(formula): 18 formula = re.sub(' ', '', formula) 19 formula_ret = 0 20 match_brackets = re.search(r'\([^()]+\)', formula) 21 if match_brackets: 22 calc_result = calc(match_brackets.group().strip("(,)")) 23 formula = formula.replace(match_brackets.group(), str(calc_result)) 24 return calc(formula) 25 else: 26 formula = formula.replace('--', '+').replace('++', '+').replace('-+', '-').replace('+-', '-') 27 while re.findall(r"[*/]", formula): 28 get_formula = re.search(r"[.\d]+[*/]+[-]?[.\d]+", formula) 29 if get_formula: 30 get_formula_str = get_formula.group() 31 if get_formula_str.count("*"): 32 formula_list = get_formula_str.split("*") 33 ret = float(formula_list[0]) * float(formula_list[1]) 34 else: 35 formula_list = get_formula_str.split("/") 36 ret = float(formula_list[0]) / float(formula_list[1]) 37 formula = formula.replace(get_formula_str, str(ret)).replace('--', '+').replace('++', '+') 38 formula = re.findall(r'[-]?[.\d]+', formula) 39 for num in formula: 40 formula_ret += float(num) 41 return formula_ret 42 # calc_str = input('>>>') 43 calc_str = '1-2*((60-30+(-40---5)*(9-2*5/3+7/3*99/4*2998+ 10*568/ 14))-(-4*3)/(16-3*2))' 44 formula_result = calc(calc_str) 45 print(formula_result)