Import reres= ' 1-2 * ((60-30 + (9-2*5/3 + 7/3*99/4*2998 +10 * 568/14) * ( -40/5))-( -4*3)/(16-3*2)) ' Res=res.replace ( ",") Print (eval (res)) # Print (Re.findall (R '-?[ \d\.] +|\+|\-|\*|/', res)) def grep (list): #过滤符号 list=list.replace ("+ +", "+") list=list.replace (' +-', '-') list=list.re Place ('-+ ', '-') list=list.replace ('--', ' + ') return listdef Jisuan (list,x): #计算乘除 index=list.index (x) if x== ' * ': num=float (List[index-1]) *float (list[index+1]) else:num=float (list[index-1])/float (list[index+1]) Del List[index-1],list[index-1],list[index-1] List.insert (INDEX-1,STR (num)) return listdef jisuan2 (list): #计算加减 Index=list.index (' + ') num = float (list[index-1]) +float (List[index + 1]) del list[index-1], list[index-1], List[index-1] List.insert (index-1, str (num)) return listdef Pangduan (list): #判断计算先后顺序 while 1:if ' * ' in list and '/' is List:jisuan (list, ' * ') elif '/' in List and ' * ' Not In List:jisuan (list, '/') elif ' * ' in the list and '/' in List:a=list.index (' * ') b=list. Index ('/') if A>b:jisuan (list, ' * ') Else:jisuan (list, '/') E Lif ' + ' in list:jisuan2 (list) Else:num = 0 for i in List:num+=flo at (i) Return numdef Zhaokuohao (string): #寻找所有里层括号, and parentheses and evaluates the result Res1=re.search (' \ ([^ ()]+\) ', string) if Res1 : Kuohao=res1.group () Mylist=re.findall (R '-?[ \d\.] +|\+|\-|\*|/', Res1.group ()) X=pangduan (mylist) string=string.replace (KUOHAO,STR (x)) # Print (x) String=grep (String) # Print (string) return Zhaokuohao (String) Else: # Print (String) retur N Stringdef End (string): #处理剩下无括号的外层 B=re.findall (R '-?[ \d\.] +|\+|\-|\*|/', string) print (Pangduan (b)) End (Zhaokuohao (res)) End (Zhaokuohao (' + + '))
Write a calculator in Python