Python Practice---Simulation calculator

Source: Internet
Author: User
Tags arithmetic

#!/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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.