计算器(第一版)
#!/usr/bin/env python # -*- coding:utf-8 -*- # by wk #1 - 2 * ( (60-30 +(-9-2-5-2*3-5/3-40*4/2-3/5+6*3) * (-9-2-5-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) ) import re def Remove_parentheses(my_cal): new_cal = re.search("\([^()]*\)",my_cal) new_cal2 = new_cal # print(new_cal2) # new_cal3 = re.search("[^(].*[^)]",new_cal2) return new_cal2 def Calculation(old_my_cal): new_cal6 = Remove_duplicates(old_my_cal) new_cal5 = re.search("[^(].*[^)]", new_cal6) # print('gjgkjh',new_cal5.group()) new_cal,new_cal4 = Remove_dupli_md(new_cal5.group()) # new_cal = re.split("[+-]",new_cal5.group()) # new_cal4 = re.findall("[+-]",new_cal5.group()) print('t1',new_cal) print('t2',new_cal4) new_cal,new_cal4 = Remove_spaces(new_cal,new_cal4) print('list',new_cal) # print(new_cal4) for k,v in enumerate(new_cal): if '*' in v or '/' in v: new_cal2 = re.split("[*/]",v) new_cal3 = re.findall("[*/]",v) # print(new_cal2) # print(new_cal3) res = None for k2,v2 in enumerate(new_cal2): if res: if new_cal3[k2-1] == '*': res *= float(v2) elif new_cal3[k2-1] == '/': res /= float(v2) else: res = float(v2) new_cal[k] = res # print('a',new_cal,'b',new_cal4) result_as = Add_subtract(new_cal, new_cal4) return result_as def Add_subtract(my_cal,my_cal2): # print('aaa',my_cal) # print('bbb',my_cal2) res = None for k,v in enumerate(my_cal): if res: if my_cal2[k-1] == '+': res += float(v) elif my_cal2[k-1] == '-': res -= float(v) else: res = float(v) # print('+++',res) return res def Remove_duplicates(formula): #过滤符合 formula = formula.replace("++", "+") formula = formula.replace("+-", "-") formula = formula.replace("-+", "-") formula = formula.replace("--", "+") formula = formula.replace("- -", "+") return formula def Remove_dupli_md(str1): #合并乘除后的加减 res = re.split("[+-]", str1) res2 = re.findall("[+-]", str1) for k, v in enumerate(res): if v.endswith("*") or v.endswith("/"): res[k] = res[k] + res2[k] + res[k + 1] del res[k + 1] del res2[k] return res,res2 def Remove_spaces(my_list,my_list2): #过滤掉开头的空格 if my_list[0] == '': my_list[1] = my_list2[0] + my_list[1] del my_list[0] del my_list2[0] return my_list,my_list2 if __name__ == '__main__': my_cal = "1-2*(( 60-30+(-9-2-5-2* 3-5/3-40*4/2-3/5+6*3)*(-9 -2-5-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))" # result_as = Add_subtract(result_md,result_md2) parenthesise_flag = True while parenthesise_flag: # print('zzz',my_cal) result1 = Remove_parentheses(my_cal) # print('re',result1.group()) if result1: result_as = Calculation(result1.group()) # print('as',result_as) my_cal = my_cal.replace(str(result1.group()),str(result_as)) print('new cal',my_cal) else: print('\033[41;1m----没拓号了...---\033[0m') # print('\n\n\033[42;1m最终结果:\033[0m', compute(formula)) print('end',my_cal) new_my_cal = Remove_duplicates(my_cal) print(new_my_cal) res = Calculation(new_my_cal) print('res',res) parenthesise_flag = False