Posting on blog for the first time.
In the online course of reading, you need to edit a calculator to be able to calculate negative numbers and parentheses.
Think about it, regular module just learned. Think about editing it. The first idea is to do a function and realize four operations. Matching symbols and numbers with regularity
1 def size(ch): #Define four basic operations for basic calculation 2 list_num=re.split('[-,+,*,/]',ch) #A number that defines an object to receive all operations 3 list_sym=re.findall('\+|-|\*|/',ch)#A symbol that defines an object to receive all operations 4 num=0 5 list_del=[] 6 for i in list_sym: 7 if i=='/'or i=='*':#Judge whether there is multiplication or division. 8 if i=='*':#If so, multiply and divide in order 9 list_num[num]=str(int(float(list_num[num]))*int(float(list_num[num+1]))) 10 elif i=='/': 11 list_num[num]=str(int(float(list_num[num]))/int(float(list_num[num+1]))) 12 del list_num[num+1]#Delete the next element 13 list_del.append(num)#Where to store symbols to be deleted 14 num-=1#Delete an element corresponding to the above and below num Reduce 1 so that the position of the deleted symbol is exactly corresponding 15 num+=1 16 for i in list_del: 17 del list_sym[i] 18 del list_del #Remove empty list 19 num=0 20 for i in list_sym: 21 if i =='+' or i =='-': 22 if i=='+':#Add and subtract in order if any 23 list_num[num]=str(int(float(list_num[num]))+int(float(list_num[num+1]))) 24 elif i=='-': 25 list_num[num]=str(int(float(list_num[num]))-int(float(list_num[num+1]))) 26 del list_num[num+1]#Delete the next element 27 num-=1 28 num+=1 29 del list_sym #Remove symbol list 30 return list_num[0] #Return calculated value #Can't have a negative low-end version
However, there is a drawback to this, that is, negative sign cannot be calculated, which is a headache.
Then there is the improved version, which directly receives various data symbols with a list. In addition, only multiplication and division are considered, and addition and subtraction are not considered. After addition, traversal list is directly used, and subtraction is directly followed by data multiplication and division.
1 def size(ch): #Define four basic operations for basic calculation 2 list_num=re.findall('(\d+|-\d+|/|\*)',ch) #Define an object to receive all operands 3 num=0 4 list_del=[]#Based on the basic principle of four operations, no matter addition or subtraction is only about multiplication and division, the final result is added in the list, and the minus sign is treated as data directly. 5 for i in list_num: 6 if i=='/'or i=='*':#Judge whether there is multiplication and division 7 if i=='*':#If so, multiply and divide in order 8 list_num[num+1]=str(int(float(list_num[num-1]))*int(float(list_num[num+1]))) 9 elif i=='/': 10 list_num[num+1]=str(int(float(list_num[num-1]))/int(float(list_num[num+1]))) 11 list_del.append(num-1) 12 list_del.append(num)#Record the first two elements to be deleted 13 num+=1 14 m=0 15 for i in list_del: 16 del list_num[i-m] 17 m+=1#Self reduction is required when deleting, otherwise large data will be deleted repeatedly. 18 del list_del #Remove empty list 19 sum=0 20 for j in list_num: 21 sum+=int(float(j)) 22 return sum #Return calculated value
Then we need to consider matching the contents in brackets.
How to match? To match the inner bracket, another way is to make the bracket have no other brackets.
date_m=re.search('\([^()]+\)',date).group()#Inner bracket and inner data of regular matching
There are also a variety of problems to consider, in this list of two, remove the space in the input string, and change the + and - connection to-
date=re.sub('\s*','',date)#Remove space from input string date=re.sub('\+-|-\+','-',date)#Remove+-Symbol linking
Complete code
1 import re 2 def size(ch): #Define four basic operations for basic calculation 3 list_num=re.findall('(\d+|-\d+|/|\*)',ch) #Define an object to receive all operands 4 num=0 5 list_del=[]#Based on the basic principle of four operations, no matter addition or subtraction is only about multiplication and division, the final result is added in the list, and the minus sign is treated as data directly. 6 for i in list_num: 7 if i=='/'or i=='*':#Judge whether there is multiplication and division 8 if i=='*':#If so, multiply and divide in order 9 list_num[num+1]=str(int(float(list_num[num-1]))*int(float(list_num[num+1]))) 10 elif i=='/': 11 list_num[num+1]=str(int(float(list_num[num-1]))/int(float(list_num[num+1]))) 12 list_del.append(num-1) 13 list_del.append(num)#Record the first two elements to be deleted 14 num+=1 15 m=0 16 for i in list_del: 17 del list_num[i-m] 18 m+=1#Self reduction is required when deleting, otherwise large data will be deleted repeatedly. 19 del list_del #Remove empty list 20 sum=0 21 for j in list_num: 22 sum+=int(float(j)) 23 return sum #Return calculated value 24 while True: 25 date=input('Enter a string to evaluate the number:') 26 date=re.sub('\s*','',date)#Remove space from input string 27 date=re.sub('\+-|-\+','-',date)#Remove+-Symbol linking 28 if re.search('[a-zA-Z]',date)!=None: #Matching letters 29 print('Letters cannot be entered') 30 else: 31 if len(re.findall('\(',date))!=len(re.findall('\)',date)): #Find the length of two matching lists 32 print('Inconsistent left and right parentheses') 33 else: 34 while True: 35 if re.search('\(',date)!=None: 36 date_m=re.search('\([^()]+\)',date).group()#Inner bracket and inner data of regular matching 37 date_x=re.sub('\(|\)','',date_m)#Regular match remove bracket 38 date_n=re.sub('\+','\+',date_m) 39 date_n=re.sub('\*','\*',date_n) 40 date_n=re.sub('\(','\(',date_n) 41 date_n = re.sub('\)', '\)', date_n)#Generalize special characters 42 date=re.sub(date_n,str(size(date_x)),date)#Computes the characters in parentheses and replaces the original string 43 else: 44 print(size(date))#Output result 45 break #Exit loop 46 47 #Since it is not a decimal type, there is a deviation in the output result.
This code can only calculate integer type, if decimal operation may report error or output error.