#!/bin/env python#-*-coding:utf-8-*-" "The implementation can calculate a formula like 1-2 * ((60-30 + ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 +10 * 568/14))-( -4*3)/(16-3*2) )" "ImportRea=r'1-2 * ((60-30 + ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 +10 * 568/14))-( -4*3)/(16-3*2) )'#*/Arithmetic functiondefChengchu (str): Calc= Re.split ("[*/]", str)#use */split formulaOP = Re.findall ("[*/]", str)#Find all * and/numbersRET =None forIndex,iinchEnumerate (Calc):ifret:ifOP[INDEX-1] = ="*": Ret*=float (i)elifOP[INDEX-1] = ="/": Ret/=float (i)Else: Ret=float (i)returnret#Remove the repeat operation, and handle the special column +-symboldefdel_double (str): STR= Str.replace ("++","+") Str= Str.replace ("--","-") Str= Str.replace ("+-","-") Str= Str.replace ("- -","-") Str= Str.replace ("+ +","+") returnStr#Calculating the main control functiondefCalc_contrl (str): Tag=False str= Str.strip ("()")#Remove the outermost bracketsstr = del_double (str)#calling functions to handle repetitive operationsFind_ = Re.findall ("[+-]", str)#get all + + operatorsSplit_ = Re.split ("[+-]", str)#regular processing is split with the-+ operator and only the */operator is left after splitting ifLen (Split_[0].strip ()) = = 0:#Special HandlingSPLIT_[1] = find_[0] + split_[1]#a "-" condition before the first number is processed, and a new signed number is obtained . #The case of a negative "-" before the first digit is processed, and may be marked with "-" after the operator ifLen (split_) = = 3 andLen (find_) ==2: Tag=TruedelSPLIT_[0]#Delete the original split number delFind_[0]Else: delSPLIT_[0]#Delete the original split number delFIND_[0]#Delete original split operator forIndex, IinchEnumerate (split_):#Remove arithmetic numbers with * or/end ifI.endswith ("* ")orI.endswith ("/ "): Split_[index]= Split_[index] + Find_[index] + split_[index+1] delSplit_[index+1] delFind_[index] forIndex, IinchEnumerate (split_):ifRe.search ("[*/]", i):#first calculate the formula containing * /Sub_res = Chengchu (i)#Call the remaining functionSplit_[index] =Sub_res#re-calculation plus minusres =None forIndex, IinchEnumerate (split_):ifRes:ifFIND_[INDEX-1] = ="+": Res+=float (i)elifFIND_[INDEX-1] = ="-": #If two negative numbers are subtracted, they are added or subtracted ifTag = =True:res+=float (i)Else: Res-=float (i)Else: #case where I is empty when processing without parentheses ifI! ="": Res=float (i)returnResif __name__=='__main__': whileTrue:calc_input= Input ("Please enter a calculation formula \ n default to:%s:"%a). Strip ()Try: ifLen (calc_input) = =0:calc_input=a calc_input= R'%s'%calc_input#do special treatment to keep the character prototypeFlag = True#Initialize flag bitresult = None#Initialize the results of the calculation #cyclic processing of parentheses whileFlag:inner= Re.search ("\([^()]*\)", Calc_input)#get the single content within the innermost brackets first #print (Inner.group ()) #calculated when parentheses are available ifInner:ret= Calc_contrl (Inner.group ())#call the Calculate control functionCalc_input = Calc_input.replace (Inner.group (), str (ret))#Replace the result of the operation with the corresponding string at the original processing index value Print("processing the operation in parentheses [%s] The result is:%s"%(Inner.group (), str (ret) ))#flag = True #Calculate without parentheses Else: Ret=Calc_contrl (calc_input)Print("\033[0;31m Final calculation results are:%s\033[0m"%ret)Print("\033[0;32meval calculation result:%s\033[0m"%eval (calc_input))#End Calculation FlagFlag =Falseexcept: Print("you entered the wrong formula, please re-enter! ")
Python Practice---Simulation calculator