Python Scientific calculator (calculator)

Source: Internet
Author: User

Description

The calculator is written primarily to practice regular expressions and Python basics: code comparison low!

Run process
Enter your calculation formula and the calculator will output the results to the screen (the steps will be printed here); Exit (Exit/quit)
Mycalc> 1-2 * ((60-30 + ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 +10 * 568/14))-( -4*3)/(16-3*2)) 1-2* ((60-30+ ( -40/5) * ( 9-2*5/3+7/3*99/4*2998+10*568/14))-( -4*3)/(16-3*2))-----------steps [] [' -40/5 '] ( -40/5) Results: -8.0parenthesis_calc_ Result:1-2* ((60-30+-8.0* (9-2*5/3+7/3*99/4*2998+10*568/14))-( -4*3)/(16-3*2))-----------steps ['-', ' + ', ' + '] [' 9 ', ' 2*5 /3 ', ' 7/3*99/4*2998 ', ' 10*568/14 '] (9-2*5/3+7/3*99/4*2998+10*568/14) operation Result: 173545.88095238098parenthesis_calc_ Result:1-2* ((60-30-8.0*173545.88095238098)-( -4*3)/(16-3*2))-----------steps ['-', '-'] [' 60 ', ' 30 ', ' 8.0* 173545.88095238098 '] (60-30-8.0*173545.88095238098) operation results: -1388337.0476190478parenthesis_calc_result:1-2* (- 1388337.0476190478-( -4*3)/(16-3*2))-----------steps [] [' -4*3 '] ( -4*3) Results: -12.0parenthesis_calc_result:1-2* (- 1388337.0476190478--12.0/(16-3*2))-----------steps ['-'] [' 16 ', ' 3*2 '] (16-3*2) operation results: 10.0parenthesis_calc_result:1-2* ( -1388337.0476190478+12.0/10.0)-----------steps [' + '] ['-1388337.0476190478 ', ' 12.0/10.0 '] ( -1388337.0476190478+12.0/10.0) operation Result: -1388335.8476190479parenthesis_calc_result:1-2*-1388335.8476190479-----------Step ['-'] [' 1 ', ' 2*- 1388335.8476190479 ']1-2*-1388335.8476190479 operation results: 2776672.6952380957 The result of the final operation: 2776672.6952380957

  

Specific code implementation
#/usr/bin/env python3# _*_ coding:utf-8 _*___author__ = ' Rianley cheng ' __blog__ = ' Https://www.cnblogs.com/rianley ' Left are too short, I use Python! Data normalization, regular splitting, combining operation printing operation expressions and Operation steps ' Import re,timedef math_legal (num): #判断输入公式是否合法, such as containing characters or Special characters, do special processing try:num = float (num) return True except (valueerror,typeerror) as Diag:passdef CA Lc_formula (Formula): #替换多余的加减操作 formula = Formula.replace ("+ +", "+") formula = Formula.replace ("+-", "-") Formul A = Formula.replace ("-+", "-") formula = Formula.replace ("--", "+") return formuladef Match_calc_formula (parenthesis Es_formula): #匹配加减操作符和加减表达式列表 # Remove all of the "-+" numbers in the parentheses expression, save as a list, such as ['-', ' + ', ' + '] # with the "+ +" sign as the delimiter, the multiplication expression in parentheses is taken out and saved in the form of a list, such as [' 9 ', ' 2*5/3 ', ' 7/3*99/4*2998 ', ' 10*568/14 '] Parenthesises_formula = Re.sub ("[()]", "", Parenthesises_formula) Plusminu S_operator_list = Re.findall ("[+ +]", parenthesises_formula) plusminus_expression_list = Re.split ("[+ +]", Parenthesises_formula) If Plusminus_expRession_list[0] = "": #圆括号表达式列表中, if the first element is empty, the first element is a negative number, then the "-" sign begins with the first "-" sign merged into the first element of the list Plusminus_expression_li ST[1] = plusminus_operator_list[0] + plusminus_expression_list[1] del plusminus_expression_list[0] del PLUSM        Inus_operator_list[0] for I, E in Enumerate (plusminus_expression_list): #处理成正确的结果: [' 1 *-2 ', ' 3 *-5 ', ' 6/-3 '] E = E.strip () if E.endswith ("*") or E.endswith ("/"): Try:plusminus_expression_list [i] = Plusminus_expression_list[i] + plusminus_operator_list[i] + plusminus_expression_list[i + 1] del Plus                Minus_expression_list[i + 1] del plusminus_operator_list[i] except Indexerror as Diag: Pass return plusminus_operator_list,plusminus_expression_listdef Matching_multiply_divide_operator (Plusminus_equa tions): #匹配乘除操作符和乘除表达式列表 operator_list = Re.findall ("[*/]", plusminus_equations) value_list = Re.split ("[*/]", plus Minus_equations) RetuRN operator_list,value_listdef Plus_minus_calc (plusminus_operator_list,plusminus_expression_list): #加减运算 " Add and subtract operations to an arithmetic formula, return the result of "Plusminus_result = None for I, E in Enumerate (plusminus_expression_list): match = Math_                     Legal (e) if match = = True:if Plusminus_result:if plusminus_operator_list[i-1] = = "+":                    Plusminus_result + = float (e) elif plusminus_operator_list[i-1] = = "-": Plusminus_result-= float (e) Else:plusminus_result = float (e) Else:prin            T ("\33[33;0m input formula contains non-numeric characters!\33[0m") print ("\33[33;0m attempt operation:%s\33[0m"% e) e = re.sub ("\d", "", e)                    If E = = "": E = 0 if plusminus_result:if plusminus_operator_list[i-1] = = "+": Plusminus_result + = float (e) elif plusminus_operator_list[i-1] = = "-": Plus          Minus_result-= float (e)  Else:try:plusminus_result = float (e) except ValueError as Diag: Print ("\33[33;1m Invalid input! \33[0m ") return plusminus_resultdef Multiply_divide_calc (multiply_divide_operator_list,multiply_divide_value_list ): #乘除运算 ' multiplication operation on the formula, return multiplication result ' Multiply_divide_result = None for I, Num in enumerate (multiply_divide_value_li ST): match = Math_legal (num) If match = = True:if Multiply_divide_result:if Multi PLY_DIVIDE_OPERATOR_LIST[I-1] = = "*": Multiply_divide_result *= float (num) elif Multip                    LY_DIVIDE_OPERATOR_LIST[I-1] = = "/": Try:multiply_divide_result/= float (num)                        Except Zerodivisionerror as Diag:multiply_divide_result = 0 Print ("\33[33;0m input formula has a divisor of 0, re-enter!")  \33[0m ") Else:multiply_divide_result = float (num)      Else:print ("\33[33;0m input formula has unrecognized content!\33[0m") print ("\33[33;0m try to calculate for you:%s\33[0m"% num) num = re.sub ("\d", "", num) if num = = "": num = 1 if multiply_divide_result:if MULTIPLY_DIVIDE_OPERATOR_LIST[I-1] = = "*": Multiply_divide_result *= float (num) elif m                ULTIPLY_DIVIDE_OPERATOR_LIST[I-1] = = "/": Multiply_divide_result/= float (num) Else:                    Try:multiply_divide_result = float (num) except ValueError as Diag: Print ("\33[33;1m Invalid input! \33[0m ") return multiply_divide_resultdef Calculating_priority_formulas (priority_formula): #计算圆括号表达式" "" "" "Plus Minus_operator_list, plusminus_expression_list = Match_calc_formula (priority_formula) print ("-----------") print ("\ 33[31;1m step \33[0m ") print (Plusminus_operator_list, plusminus_expression_list) for index, equations in enumerate (Plusminus_expression_list): If "*" in Equations or "/" in Equations: "" "" "" Multiply_divide_o Perator_list, multiply_divide_value_list = Matching_multiply_divide_operator (equations) Multiply_divide_result = Multiply_divide_calc (multiply_divide_operator_list, multiply_divide_value_list) #取出乘除表达式进行乘除运算 Plusminus_exp Ression_list[index] = Multiply_divide_result Plus_minus_result = Plus_minus_calc (Plusminus_operator_list, Plusminus_ Expression_list) #将乘除的结果进行加减运算 print ("%s operation result:%s"% (Priority_formula, Plus_minus_result)) return Plus_minus_resu Ltdef start_operation (Formula): "" "Operation Main program entrance, processing the input mathematical formula, matching the lowest-level parenthesis expression, and give multiplication function to calculate the return result, replace the parentheses expression" "" formula = Formula.rep  Lace ("", "") #去掉表达式多余的空格 formula = Calc_formula (Formula) #去掉表达式里重复的 "+-" print (Formula) Parenthesises_flag = True while Parenthesises_flag:formula = Calc_formula (Formula) Parenthesis_formula = Re.search (r "\ ([^ ()] ]+) \) ", formula) ifParenthesis_formula:parenthesis_formula = Parenthesis_formula.group () Parenthesis_calc_result = cal Culating_priority_formulas (parenthesis_formula) formula = Formula.replace (Parenthesis_formula, str (parenthesis_ Calc_result)) Print ("Parenthesis_calc_result:%s"% formula) Else:calc_result = Calculating_ Priority_formulas (Formula) Parenthesises_flag = False print ("Result of last operation: \33[31;1m%s\33[0m"% Calc_resu LT) def Mycalcmain (): prompt = "' Enter your calculation formula and the calculator will output the results to the screen (the steps will be printed here); Exit (Exit/quit) Example formula: 1-2 * ((60-30 + ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 +10 * 568/14))-( -4*3)/(16-3*2)) ' Print (            prompt) While True:formula = input ("mycalc>"). Strip () if formula = = "Exit" or formula = = "Quit": Print (' Welcome to the next use, Welcome to the author Blog!            (Https://cnblogs.com/rianley) For more information please expect ') Time.sleep (3) exit ("Bye.bye ...") elif formula = = "":          Continue else:  Start_operation (Formula) If __name__ = = ' __main__ ': Mycalcmain () 

  

Knot words

Try to become the person you want to be, even if you fail at last! It doesn't matter, because failure is more terrible than regret!

Python Scientific calculator (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.