1 # Author : Kelvin 2 # Date : 2019/1/10 12:36 3 4 # 实现计算器功能(加减乘除) 例如:2+(5*2)-(6/2*(5-1))) 4+2*3 1+(2*(3-1))+(2*(1+2)) 5 import re 6 #①计算不包含括号的运算 7 def simple(equation): 8 # 先判断是否存在 * / 运算 9 flag=re.findall("*|/",equation) 10 if flag: 11 res_s1 = re.findall("(d+.d+|d+|+|-|*|/)", equation) #查找所有的数字 加减乘除符号 12 # print("simple:", res_s1) 13 list_dig1 = [i for i in res_s1 if i not in ["+", "-", "*", "/"]] 14 list_mod1 = [i for i in res_s1 if i in ["+", "-", "*", "/"]] 15 for i in range(len(list_mod1)): 16 if list_mod1[i] in ["/", "*"]: 17 mul1 = list_dig1[i] 18 mul2 = list_dig1[i + 1] 19 if list_mod1[i] is "/": 20 list_list1 = [mul1, "/", mul2] 21 res_str1 = "".join(list_list1) 22 # print(res_str) 23 res_res1 = str(float(mul1) / float(mul2)) 24 # print(res_res1) 25 # print(type(res_res1)) 26 equation = equation.replace(res_str1, res_res1) 27 # print(equation) 28 else: 29 if list_mod1[i] is "*": 30 list_list1 = [mul1, "*", mul2] 31 res_str = "".join(list_list1) 32 # print(res_str) 33 res_res1 = str(float(mul1) * float(mul2)) 34 # print(res_res1) 35 # print(type(res_res1)) 36 equation = equation.replace(res_str, res_res1) 37 # print(equation) 38 #下面是处理没有 * / 之后的运算 39 res_s2 = re.findall("(d+.d+|d+|+|-)", equation) 40 # print("+ -:", res_s2) 41 list_dig2 = [i for i in res_s2 if i not in ["+", "-"]] 42 list_mod2 = [i for i in res_s2 if i in ["+", "-"]] 43 result=list_dig2[0] 44 # print(list_dig2) 45 # print(list_mod2) 46 for i in range(1,len(list_dig2)): 47 m=list_mod2[i-1] 48 if m=="+": 49 result=float(result)+float(list_dig2[i]) 50 else: 51 result=float(result)-float(list_dig2[i]) 52 # print("最终结果:",result) 53 return result 54 55 56 57 58 #②计算包含括号的运算 59 def trouble(equation): 60 tro_res1=re.findall("([^()]*)",equation) 61 # print(tro_res1) 62 if tro_res1: 63 for i in tro_res1: 64 a=re.findall("[^(^)]",i) 65 b="".join(i) 66 # print("b:",b) 67 res_temp=str(simple(b)) 68 equation=equation.replace(i,res_temp) 69 # print(equation) 70 # print(equation) 71 else: 72 return simple(equation) 73 74 return trouble(equation) #递归调用trouble函数,直到所有括号全部处理完毕 75 76 77 78 79 80 #③计算器的主方法 81 def cal(equation): 82 equation = equation.replace(" ", "") # 去除算式字符串中的空格 (过滤杂质) 83 res1=re.findall("[a-zA-Z@$%^&!]",equation) 84 # print(res1) 85 if res1: 86 print("算式输入有误,请重试!") 87 else: 88 cal_flag=re.findall("(",equation) 89 if cal_flag: 90 return trouble(equation) 91 else: 92 return simple(equation) 93 94 95 96 #④测试代码 97 if __name__=="__main__": 98 s = input("请输入算式:") 99 result=cal(s) 100 print("%s 运算结果:"%s,result) 101 # 1+(2*(2+1))+(2/(4*2))运算结果: 7.25 1+(2+4*2)运算结果: 11.0 1+(2*(2+1))+(2/(4*2))-(2-(4/(2*2)))运算结果: 6.25