Python Development Program: Calculator

Source: Internet
Author: User

Develop a simple Python calculator

    1. Implementation of subtraction and extension priority resolution
    2. User Input 1-2 * ((60-30 + ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 +10 * 568/14))-( -4*3)/(16-3*2)) and other similar formulas, you must parse the inside (), +,-, *,/character Number and formula (cannot call Eval and other similar functions lazy implementation), the result of the operation, the results must be consistent with the results of the actual calculator

#!/usr/bin/env python#-*-coding:utf-8-*-#-author-lianimport redef operator_update (Formula): # Remove NULL characters from formula formula, update operation Operator processing formula = Formula.replace ("", "") # removes the null character formula=formula.replace ("+-", "-") formula=formula.replace ("--", "+") return formuladef Calc_muldiv (formula_list): "The multiplication in the calculation formula:p Aram formula: List: return: ' For I Ndex,element in Enumerate (formula_list): if ' * ' in element or '/' in Element:operators=re.findall ("[* *]                 ", Element) Calc_list=re.split (" [*/] ", element) num = None for i,e in Enumerate (calc_list):                    If num:if operators[i-1] = = "*": num *= float (e) Elif Operators[i-1] = = "/": num/= float (e) else:num = Floa    T (e) formula_list[index] = num return formula_listdef calc_plumin (operators,num_list): "' Calculates the addition and subtraction of the list number :p Aram operators: List of operators    :p Aram Num_list: A list of the numbers for the operation: return: Returns the result of the calculation ' num = None for I, E in Enumerate (num_list): If num:                If operators[i-1] = = "+": num + = float (e) elif operators[i-1] = = "-": num-= float (e) Else:num = float (e) return numdef merge (plus_minus_operator,multiply_divide_list ): ' Put the list in such a form ' -3* ' ' 5/3* ' 4/2 ' into a piece:p Aram Formula_list:: Return: "' for index, element in ENU Merate (multiply_divide_list): If Element.endswith ("*") or Element.endswith ("/"): Multiply_divide_list[in            Dex] = element + Plus_minus_operator[index] + multiply_divide_list[index+1] del multiply_divide_list[index+1] Del Plus_minus_operator[index] return merge (plus_minus_operator,multiply_divide_list) return Plus_ Minus_operator,multiply_divide_listdef Bracket_calc (Formula): "Calculates the formula formula for the most inner layer of parentheses:p Aram formula:: Return : "' formula = RE. Sub ("[()]", "" ", Formula) # Remove both sides of () formula = Operator_update (Formula) Plus_minus_operator = Re.findall (" [+ +] ", form ULA) #列表 ' + '-' operator multiply_divide_list = Re.split ("[+ +]", formula) #列表 have ' * '/' if Multiply_divide_li        St[0] = = "": #multiply_divide_list列表第一个字符为空的话, indicating a number of minus multiply_divide_list[1] = "-" + multiply_divide_list[1] Del plus_minus_operator[0] del multiply_divide_list[0] res = merge (Plus_minus_operator,multiply_divide_lis T) plus_minus_operator=res[0] #列表 ' + '-' operator for merging Multiply_divide_list=res[1] Plus_minus_list=calc _muldiv (multiply_divide_list) #生成只进行加减运算的列表 res=calc_plumin (plus_minus_operator,plus_minus_list) return RESDE F Calculate (Formula): "The main entrance of the calculation program, the main logic is to calculate the value in the extension number, calculated and then calculate the multiplication, and then add and subtract" while true:formula_depth = Re.search ("\ ([^ ( )]+\) ", formula) if Formula_depth:formula_depth=formula_depth.group () Res=bracket_calc (formu la_depth) forMula=formula.replace (Formula_depth,str (res)) print ("\33[34;1m%s\33[0m"% (Formula)) Else:res = Bracket_calc (Formula) print ("\33[31;1m result:%s\33[0m"% (res)) exit () if __name__ = = ' __main__ ': formu La = "1-2 * ((60-30 + ( -9-2-5-2*-3-5/3-40*4/2-3/5+6*3) * ( -9-2-5-2*5/3 + 7/3*99/4*2998 +10 * 568/14))-( -4*3)/(16-3*  2) "Calculate (Formula) #1-2 * ((60-30 +-74.26666666666667 * ( -9-2-5-2*5/3 + 7/3*99/4*2998 +10 * 568/14))-( -4*3)/ (16-3*2)) #1-2 * ((60-30 +-74.26666666666667 * 173520.88095238098)-( -4*3)/(16-3*2)) #1-2 * (-12886787.425396826-( -4*3)/(16 -3*2)) #1-2 * ( -12886787.425396826--12.0/(16-3*2)) #1-2 * ( -12886787.425396826--12.0/10.0) #1-2 *-12886786.22 5396827# Results: 25773573.450793654

  

Python Development Program: 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.