1. 程式人生 > >正則計算器2

正則計算器2

none img nis true ret zhong lose eval RM

 1 import sys
 2 import re
 3 
 4 def deal_fuhao(calc_list):
 5     new_calc_list=[]
 6     for index,item in enumerate(calc_list):
 7         if item.strip().endswith(*) or item.strip().endswith(/):
 8             new_calc_list.append(%s-%s%(calc_list[index],calc_list[index+1]))
 9         elif
(*or/) in item: 10 new_calc_list.append(item) 11 print(new_calc_list) 12 return new_calc_list 13 14 def jianfa(formula): 15 print(運算,formula) 16 print(formula) 17 formula = formula.replace(+-, "-") 18 formula = formula.replace(++, "+") 19 formula = formula.replace(
-+, "-") 20 formula = formula.replace(--, "+") 21 22 calc_list=re.split([+-],formula) 23 sub_calc_list = re.findall([+-], formula) 24 print(calc_list,sub_calc_list) 25 sub_res=None 26 for index,item in enumerate(calc_list): 27 if sub_res: #這不是第一次 28 if
sub_calc_list[index-1]=="-": 29 sub_res -= float(item) 30 else: 31 sub_res += float(item) 32 else: 33 sub_res=float(item) #這裏其實就是賦值,然後用於上邊的計算 34 print(\033[31;1m[%s]\033[0m %sub_res) 35 print(eval(formula)) 36 def chengchu(formula): 37 print(運算,formula) 38 calc_list=re.split([+-],formula) 39 calc_list =deal_fuhao(calc_list) 40 print(calc_list) 41 42 for item in calc_list: 43 sub_calc_list=re.split([*/],item) 44 sub_operator_list=re.findall([*/],item) 45 print(sub_calc_list,sub_operator_list) 46 sub_res=None 47 for index,i in enumerate(sub_calc_list): 48 if sub_res: #這不是第一次 49 if sub_operator_list[index-1]==*: 50 sub_res *= float(i) 51 else: 52 sub_res /= float(i) 53 else: 54 sub_res = float(i) 55 56 print(\033[31;1m[%s]=\033[0m%item,sub_res) 57 formula = formula.replace(item,str(sub_res)) 58 59 print(\033[31;1m[%s]結果\033[0m,formula) 60 res_zuizhong =jianfa(formula) 61 62 def calc(formula): 63 parentheses_flag = True 64 while parentheses_flag: 65 m=re.search(\([^()]+\),formula) 66 if m: 67 print(m.group()) 68 sub_formula=m.group().strip(()) 69 sub_res=chengchu(sub_formula) 70 break 71 72 if __name__==__main__: 73 formula = 1-2*(60-30+ (-40.0/5*(9-2*5/-3+7/3*99/4*2998+10*568/14)))-(-4*3)/(16-3*2) 74 res = calc(formula)
技術分享圖片
 1 C:\Users\qiangql\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/qiangql/PycharmProjects/untitled1/計算器2.py
 2 (9-2*5/-3+7/3*99/4*2998+10*568/14)
 3 運算 9-2*5/-3+7/3*99/4*2998+10*568/14
 4 [2*5/-3, 7/3*99/4*2998, 10*568/14]
 5 [2*5/-3, 7/3*99/4*2998, 10*568/14]
 6 [2, 5, -3] [*, /]
 7 [2*5/-3]= -3.3333333333333335
 8 [7, 3, 99, 4, 2998] [/, *, /, *]
 9 [7/3*99/4*2998]= 173134.50000000003
10 [10, 568, 14] [*, /]
11 [10*568/14]= 405.7142857142857
12 [%s]結果 9--3.3333333333333335+173134.50000000003+405.7142857142857
13 運算 9--3.3333333333333335+173134.50000000003+405.7142857142857
14 9--3.3333333333333335+173134.50000000003+405.7142857142857
15 [9, 3.3333333333333335, 173134.50000000003, 405.7142857142857] [+, +, +]
16 [173552.54761904766]
17 173552.54761904766
18 
19 Process finished with exit code 0
運算結果

正則計算器2