1.简单计算器
1 #计算一个表达式的时候,首先肯定是先算括号里面的,再算乘除法,后算加减法 2 import re 3 # 1.去括号 4 def remove_kuohao(expression): 5 ''' 6 这是一个去除括号的函数 7 :param expression: 传进来的表达式 8 :return: 计算后的结果 9 ''' 10 while True: 11 ret = re.search(r'([^(]*?)',expression) #先利用正则匹配到式子里面的括号 12 if ret: #如果有括号 13 re_expression = ret.group() #先把找到的括号group()一下得到 14 # print(re_expression) 15 res = jianhua(re_expression.strip('()')) #括号里面有*/-+都不一定,就又定义了一个简化这个表达式的函数 16 # 如果是乘法就执行乘法运算,如果是除法运算就执行除法等,这样的话就直接调用jianhua这个函数了,当然这个式子 17 # 有括号,顺便把括号也去了,直接计算去掉括号后的式子 18 expression = expression.replace(re_expression,str(res)) #把计算出来的结果放回去:就是把原来的括号里的表达式 19 # 替换成现在计算的结果 20 # print(expression) 21 continue 22 break 23 res = jianhua(expression) 24 return res 25 #简化算法 26 def jianhua(re_expression): 27 while True: 28 # 匹配乘除法 29 ret = re.search(r'd+.*?d*[*/]-?d+.?d*', re_expression) #利用正则匹配乘除法 30 if ret: # 如果匹配到有*或/就执行下面的代码 31 chengchu_expression = ret.group() #就先group一下得到有乘除法的表达式 32 res = chengchu(chengchu_expression) #调用乘除法的函数计算 33 re_expression = re_expression.replace(chengchu_expression, str(res)) #吧有乘除法的表达式和计算出来的结果替换 34 re_expression =chulifuhao(re_expression) #在调用处理符号的函数 35 # print(re_expression) 36 continue 37 break 38 # 匹配加减法 39 num = re.findall(r'[+-]?d+.?d*', re_expression)#在没有乘除法的时候,就让匹配加减法, 40 if len(num) > 1: #如果匹配到的表达式的长度大于1,不过是加法还是减法,都让计算加法。因为float啥结果就是啥 41 mynum = 0 42 for i in num: 43 mynum += float(i) 44 return mynum 45 else: 46 return num[0] 47 # 3.计算两个数的+-*/ 48 def chengchu(expression): 49 if '*' in expression: 50 x,y = expression.split('*') 51 return float(x)*float(y) #返回乘法运算的结果 ,让res接收 52 if '/' in expression: 53 x, y = expression.split('/') 54 return float(x)/float(y) #返回乘法运算的结果 ,让res接收 55 56 def chulifuhao(expression): 57 if '--' in expression: 58 expression = expression.replace('--','+') 59 if '++' in expression: 60 expression = expression.replace('++','+') 61 if '+-' in expression: 62 expression = expression.replace('+-','-') 63 if '-+' in expression: 64 expression = expression.replace('-+','-') 65 return expression #返回结果 66 67 cmd = input('请输入你要计算的表达式:>>') 68 # s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )' 69 new_s = cmd.replace(' ', '') #先将所有的空格去了 70 # print(new_s) 71 ret = remove_kuohao(new_s) #调用去除括号的函数,进行下一步操作 72 print(ret)
2.更高级的计算器
1 import re 2 from functools import reduce 3 from tkinter import * 4 '''处理特殊-号运算''' 5 6 7 def minus_operation(expresstion): 8 minus_operators = re.split("-", expresstion) 9 calc_list = re.findall("[0-9]", expresstion) 10 if minus_operators[0] == "": 11 calc_list[0] = '-%s' % calc_list[0] 12 res = reduce(lambda x, y: float(x) - float(y), calc_list) 13 print(">>>>>>>>>>>>>>减号[%s]运算结果:" % expresstion, res) 14 return res 15 16 '''reduce()对sequence连续使用function, 如果不给出initial, 则第一次调用传递sequence的两个元素, 17 以后把前一次调用的结果和sequence的下一个元素传递给function''' 18 19 '''处理双运算符号''' 20 21 22 def del_duplicates(expresstion): 23 expresstion = expresstion.replace("++", "+") 24 expresstion = expresstion.replace("--", "-") 25 expresstion = expresstion.replace("+-", "-") 26 expresstion = expresstion.replace("--", "+") 27 expresstion = expresstion.replace('- -', "+") 28 return expresstion 29 '''*/运算函数''' 30 def mutiply_dividend(expresstion): 31 calc_list = re.split("[*/]", expresstion) # 用* or /分割公式 32 operators = re.findall("[*/]", expresstion) # 找出所有*和/号 33 res = None 34 for index, i in enumerate(calc_list): 35 if res: 36 if operators[index - 1] == '*': 37 res *= float(i) 38 elif operators[index - 1] == '/': 39 res /= float(i) 40 else: 41 res = float(i) 42 procession0 = "[%s]运算结果=" % expresstion, res 43 # final_result.insert(END, procession0) # 插入窗体 44 print(procession0) 45 return res 46 47 '''处理运算符号顺序混乱情况''' 48 def special_features(plus_and_minus_operators, multiply_and_dividend): 49 for index, i in enumerate(multiply_and_dividend): 50 i = i.strip() 51 if i.endswith("*") or i.endswith("/"): 52 multiply_and_dividend[index] = multiply_and_dividend[index] + plus_and_minus_operators[index] + multiply_and_dividend[index + 1] 53 del multiply_and_dividend[index + 1] 54 del plus_and_minus_operators[index] 55 return plus_and_minus_operators, multiply_and_dividend 56 57 def minus_special(operator_list, calc_list): 58 for index, i in enumerate(calc_list): 59 if i == '': 60 calc_list[index + 1] = i + calc_list[index + 1].strip() 61 '''运算除了()的公式+-*/''' 62 def figure_up(expresstion): 63 expresstion = expresstion.strip("()") # 去掉外面括号 64 expresstion = del_duplicates(expresstion) # 去掉重复+-号 65 plus_and_minus_operators = re.findall("[+-]", expresstion) 66 multiply_and_dividend = re.split("[+-]", expresstion) 67 if len(multiply_and_dividend[0].strip()) == 0: 68 multiply_and_dividend[1] = plus_and_minus_operators[0] + multiply_and_dividend[1] 69 del multiply_and_dividend[0] 70 del plus_and_minus_operators[0] 71 plus_and_minus_operators, multiply_and_dividend = special_features(plus_and_minus_operators, multiply_and_dividend) 72 for index, i in enumerate(multiply_and_dividend): 73 if re.search("[*/]", i): 74 sub_res = mutiply_dividend(i) 75 multiply_and_dividend[index] = sub_res 76 # print(multiply_and_dividend, plus_and_minus_operators) # 计算 77 final_res = None 78 for index, item in enumerate(multiply_and_dividend): 79 if final_res: 80 if plus_and_minus_operators[index - 1] == '+': 81 final_res += float(item) 82 elif plus_and_minus_operators[index - 1] == '-': 83 final_res -= float(item) 84 else: 85 final_res = float(item) 86 procession = '[%s]计算结果:' % expresstion, final_res 87 # final_result.insert(END, procession) # 插入窗体 88 # print(procession) 89 return final_res 90 """主函数:运算逻辑:先计算拓号里的值,算出来后再算乘除,再算加减""" 91 def calculate(): 92 expresstion = expresstions.get() # 获取输入框值 93 flage = True 94 calculate_res = None # 初始化计算结果为None 95 while flage: 96 m = re.search("([^()]*)", expresstion) # 先找最里层的() 97 # pattern = re.compile(r"([^()]*)") 98 # m = pattern.match(expresstion) 99 if m: 100 sub_res = figure_up(m.group()) # 运算()里的公式 101 expresstion = expresstion.replace(m.group(), str(sub_res)) # 运算完毕把结果替换掉公式 102 else: 103 # print('---------------括号已经计算完毕--------------') 104 procession1 = "最终计算结果:%s "%figure_up(expresstion) 105 print(procession1) 106 final_result.insert(END, procession1) # 插入窗体 107 # print(' 33[31m最终计算结果:', figure_up(expresstion)) 108 flage = False 109 110 if __name__ == "__main__": 111 # res = calculate("1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )") 112 window = Tk() ###创建窗体 113 window.title('计算器') ###命名窗体 114 frame1 = Frame(window) ###框架1 115 frame1.pack() ###放置 116 frame2 = Frame(window) ###框架2 117 frame2.pack() ###放置 118 lable = Label(frame1, text="请输入公式:") ###文字标签 119 lable.pack() 120 expresstions = StringVar() ###输入框属性,字符串 121 entryname = Entry(frame1, textvariable=expresstions) ###文本输入框 122 bt_get_expresstions = Button(frame1, text="提交", command=calculate) ###按钮挂件 123 bt_get_expresstions.pack() 124 entryname.pack() 125 lable.grid_slaves(row=1,column=1) 126 entryname.grid_slaves(row=1,column=1) 127 bt_get_expresstions.grid_slaves(row=1,column=3) 128 final_result = Text(frame2) ###计算结果显示框 129 final_result.tag_config("here", background="yellow", foreground="blue") 130 final_result.pack() 131 window.mainloop() ###事件循环