简单计算器的实现:
计算:1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
#!usr/bin/env python # encoding: utf-8 import re #乘除运算 def chengchu(formula): while True: s_formula = re.search('\d+\.?\d*[*/][-]?\d+\.?\d*',formula) if s_formula: s_formula_list = re.split('[*/]',s_formula.group()) if '*' in s_formula.group(): s_sub = float(s_formula_list[0]) * float(s_formula_list[1]) formula = formula.replace(s_formula.group(),str(s_sub)) elif '/' in s_formula.group(): s_sub = float(s_formula_list[0]) / float(s_formula_list[1]) formula = formula.replace(s_formula.group(),str(s_sub)) else: print(s_formula_list,formula) res = jiajian(formula) return res #加减运算 def jiajian(formula2): if '+-' in formula2 or '++' in formula2 or '-+' in formula2 or '--' in formula2: formula2 = formula2.replace('+-', '-') formula2 = formula2.replace('++', '+') formula2 = formula2.replace('-+', '-') formula2 = formula2.replace('--', '+') while True: s_f = re.search('\d+\.?\d*[+-]\d+\.?\d*',formula2) if s_f: s_f_list = re.split('[+-]',s_f.group()) print(s_f_list) if '-' in s_f.group(): s_f_sub = float(s_f_list[0]) - float(s_f_list[1]) formula2 = formula2.replace(s_f.group(),str(s_f_sub)) elif '+'in s_f.group(): s_f_sub = float(s_f_list[0]) + float(s_f_list[1]) formula2 = formula2.replace(s_f.group(), str(s_f_sub)) continue else: print(formula2) return formula2 #开始运算 def calc(arg): while True: m = re.search("\([^()]+\)",arg) if m: formula = m.group().strip('()') print(formula) m_result = chengchu(formula) arg = arg.replace(m.group(),str(m_result)) continue else: print(arg) su = chengchu(arg) print(su) break if __name__ == "__main__": a = '1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))' # a = '1-2*-1388338.2476190478' calc(a)