习题:输入字符串计算其值:strr='1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))‘
习题之总结:
1.str是python内置函数,字符串命不能为命名str
2.字符串len和列表len长度不同
3.使用递归函数返回值
遗留问题:
1.字符串中内置多出空格导致正则表达式失效('1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) 此处有空格 )‘)。
2.字符串拆分时使用float类型计算和int 类型计算值相差比较大。
3.使用float类型计算出的值使用通用正则表达式失效。
4.计算出的结果和使用Eval()有差异,有bug?
eval计算结果:-294689
代码计算结果:-294687
附上代码,欢迎指正,谢谢!
1 import os 2 import re 3 import time 4 5 content = '1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))' 6 # eval() get value 7 print eval(content) 8 # for get sub string values 9 def countmd(str2,restr): 10 rs = re.split(restr, str2) 11 l1=rs[0:3] 12 l2 = rs[3:] 13 if l1[1].strip(' ') == "+": 14 rett = int(l1[0]) + int(l1[2]) 15 elif l1[1].strip(' ') == "--": 16 rett = int(l1[0]) + int(l1[2]) 17 elif l1[1].strip(' ') == "-": 18 rett = int(l1[0]) - int(l1[2]) 19 elif l1[1].strip(' ') == "*": 20 rett = int(l1[0]) * int(l1[2]) 21 elif l1[1].strip(' ') == "/": 22 rett = int(l1[0]) / int(l1[2]) 23 l2.insert(0,str(rett)) 24 if len(l2)>2: 25 str3="".join(l2) 26 return countmd(str3,restr) 27 else: 28 return rett 29 30 # function for get inner() values 31 def gh(strq): 32 strq=strq.strip(')').strip('(') 33 # re for add and mine 34 rejj='([\+\-\(\)]+)' 35 # re for multiply and divide 36 resc='([\/\*]+)' 37 rs2=[] 38 rs = re.split(rejj, strq) 39 for index, i in enumerate(rs): 40 if i.find('+')>0 or i.find('-')>0 or i.find('*')>0 or i.find('/')>0: 41 rs2.append(str(countmd(i.strip(')').strip('('),resc))) 42 else: 43 rs2.append(i) 44 pass 45 str4="".join(rs2) 46 rs2=filter(lambda x:x,rs2) 47 # print rs2 48 str4=str4.strip('(').strip(')') 49 if len(rs2)>2: 50 str4=countmd(str4,rejj) 51 return str4 52 else: 53 return str4 54 55 56 def mainc(ss): 57 # re for get inner () 58 rw= re.split("(\([0-9\+\-\*\/]+\))",ss) 59 for index, i in enumerate(rw) : 60 if i.startswith('(') and i.endswith(')'): 61 rw[index]=str(gh(i)).strip('') 62 rw="".join(rw) 63 if rw.find('(')>0 : 64 rw=str(mainc(rw)) 65 if rw.find('+')>0 or rw.find('-')>0 or rw.find('*')>0 or rw.find('/')>0: 66 return gh(rw) 67 else: 68 return rw 69 print mainc(content)