Design idea: First, the input formula is formatted and checked for illegal input (in this case, lowercase characters are detected), and then the re.search() method is used to match both parentheses and no parentheses (special attention is paid to matching negative numbers and decimals, and [\*] does not need to be specialized). Re.split () is used for multiplication and division, re.findall() is used for addition and subtraction, and finally, str.replace() is used to gradually update the string operation #! /usr/bin/env Python # coding=utf-8 import re def check(s): flag=True if re.search(‘[a-z]’,s): print(‘invalid input’) flag=False return flag def format(s): s = s.replace(‘ ‘, # ‘) to replace all the empty Spaces for s = s.r eplace (‘ – ‘, ‘+’) s = s.r eplace (‘ + ‘, ‘-‘) return s def count_chengchu (s) : # 45 * 25 X, y = re. The split (‘ / * / ‘s) # to assign values to the x and y if re search (‘ \ *’ s) : s = float float (x) * (y) else: s=float(x)/float(y) return s def count_jiajian(s):#45+25=70 [x,y] = re.findall(‘-? \d+\.? S =float(x)+float(y) return s exit_flag=False while not exit_flag: num = input(‘please input count_num[quit:Q]>>’) if num == ‘Q’: Print (‘thanks’) exit_flag=True elif check(num): count_end = False while not count_end: Num = format (num) if re. Search (‘ \ [[^ ()] + \] ‘, num) : # if there is the innermost parentheses count1 = re. The search (‘ \ [[^ ()] + \] ‘. Num).group() # accept the innermost parentheses like (-7.0) if re.search(‘-? \d+\.? \d*[/*]-? \d+\.? \d*’, count1): count2 = re.search(‘-? \d+\.? \d*[/*]-? \d+\.? Count3 = count_chengchu(count2) num = num.replace(count2, str(count3)) elif re.search(‘-? \d+\.? \d*[-+]-? \d+\.? \d*’, count1): count2 = re.search(‘-? \d+\.? \d*[-+]-? \d+\.? Count3 = count_jiajian(count2)# (-7) num = num.replace(count2, STR (count3) # – (7.0) else: # to brace ret1 = re search (‘ -? \d+\.? \d*’, count1).group() # 105 num = num.replace(count1, ret1)# 45-105 else:#45-2*3/3 if re.search(‘-? \d+\.? \d*[/*]-? \d+\.? \d*’, num): count2 = re.search(‘-? \d+\.? \d*[/*]-? \d+\.? Count3 = count_chengchu(count2) num = num.replace(count2, num).replace(count2, num). str(count3)) elif re.search(‘-? \d+\.? \d*[-+]-? \d+\.? \d*’, num): count2 = re.search(‘-? \d+\.? \d*[-+]-? \d+\.? Count3 = count_jiajian(count2) num = num. Replace (count2, num).replace(count2, num = num. STR (count3) print (num) count_end = True — — — — — — — — — — — — — — — — — — — — – the author: Cristano1234 source: CSDN, blog.csdn.net/clr100/arti…
Learn more about Python at gzitcast