Python-based calculator

Source: Internet
Author: User

1. Use of the knowledge points

Application of 1.python Regular expressions, re.search (' pattern ', str). Group ()

2. Use of recursion in functions

3.python function, basic syntax, control statement if ... else ..., use for loop statement

4, string formatting, concatenation of strings

5, use of the list

6.while true:statement use of dead loops

2. Code

#!/usr/bin/env python#-*-coding:utf-8-*-import re# processing multiplication def compute_mul_div (ARG): #这里需要传入1个arg列表 value = arg[0] #print Value #mch = Re.search (' \d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*] ', value) #对字符串进行乘除匹配: As 1+2*3-3, match: 2*3 MCH = re.se Arch (' \d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d* ', value) #没匹配到就直接返回 if not Mch:return #将匹配到的内容保存在content中 Conten t = Re.search (' \d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d* ', value). Group () #print content #对匹配到的内容进行 *,/judgment, and then perform the corresponding calculations, such as 2*3, first split the post-meter        Calculate If Len (Content.split (' * ')) >1:n1,n2 = Content.split (' * ') Get_value = float (N1) * Float (n2) Else: N1,N2 = Content.split ('/') Get_value = float (n1)/float (n2) #取出匹配内容两头的内容: Before,after before,after = Re.split (' \d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d* ', value,1) #然后拼接成新的字符串 new_str = "%s%s%s"% (before,get_value,after) #把n Ew_str assignment to arg[0] arg[0] = new_str #再递归进行乘除计算 compute_mul_div (ARG) #compute_mul_div (["1+2*3-4", 0]) #print compute_mu L_div ([]) #处理加减def COMPUTE_add_sub (ARG): #arg = ["3+4-2--4++2", 0] #对传进来的arg [0] expression is processed for the 1th time, the ++\--in the expression becomes the +,+-、-+ becomes-after the processing is complete, the direct break and True: If arg[0].__contains__ ('---') or arg[0].__contains__ (' +-') or arg[0].__contains__ ('--') or arg[0].__contains__ ('-+ ') ): arg[0] = Arg[0].replace ('--', ' + ') arg[0] = arg[0].replace (' +-', '-') arg[0] = Arg[0].re Place ('-+ ', '-') arg[0] = Arg[0].replace ('--', ' + ') Else:break #然后对传进来的arg [0] expression for the 2nd time, extracting the first Bit is "-" and saves the number of fetches in arg[1] #并且没提取1次: Replace "+" in the expression with "-". " -"Replace with" + ", then take arg[0] expression string 1th to the last 1 bits can be assigned to arg[0] if Arg[0].startswith ('-'): arg[1]+=1 arg[0] = Arg[0].replace ('     -', ' & ') arg[0] = arg[0].replace (' + ', '-') arg[0] = Arg[0].replace (' & ', ' + ') arg[0] = arg[0][1:] Value = Arg[0] #对字符串value进行匹配, matches the contents of the addition or subtraction, such as 1+2-3, matching 1+2 MCH = Re.search (' \d+\.*\d*[\+\-]{1}\d+\.*\d* ', value) # If it does not match, send it back directly to the if not Mch:return #将匹配的内容保存在content中, such as 1+2 content = Re.search (' \D+\.*\d*[\+\-]{1}\d+\.*\d* ', value). Group () #对匹配的内容进行计算: first judgment +,-, after the judgment to split, after the split in the +,-to calculate If Len (content.split (' + ')) &        Gt;1:n1,n2 =content.split (' + ') Get_value = float (n1) +float (n2) else:n1,n2 =content.split ('-') Get_value = float (n1)-float (N2) #取出匹配内容两头的内容, encapsulated in Before,after before,after = Re.split (' \d+\.*\d*[\+\-]{1}\d+\.* \d* ', str (value), 1) #before = Re.split (' \d+\.*\d*[\+\-]{1}\d+\.*\d* ', value,1) [0] #after = re.split (' \d+\.*\d*[\+\-]{1 }\d+\.*\d* ', value,1) [1] #将计算后的: before+ results +after, stitching, new_str = "%s%s%s"% (before,get_value,after) #再把拼接后的字符串赋值到ar    G[0], and then recursively calculate arg[0] = New_str compute_add_sub (ARG) #compute_add_sub (["1+3-2", 0]) #计算取出来的表达式 # "" "Def Compute (expr):    #先将表达式封装在inp列表中, the first element of the list represents: a pending expression, the second element represents the first number in the expression, and then we extract the number of times INP = [expr,0] #先进行乘除运算 compute_mul_div (INP) #再进行加减运算 compute_add_sub (INP) #判断inp [1] is odd or even, if odd, indicates a negative result, otherwise positive count = Divmod (inp[1],2) result = Float (INP  [0]) if count[1] = = 1:      result = result * ( -1) return result# execute take out expression def excute (expr): #匹配最里层的括号, such as: 1+2* (3/(3-2) *), the match here is (3-2) #若没括号 The direct return expression if not re.search (' \ ([[\+\-\*\/]*\d+\.*\d*] {2,}\) ', expr): Return expr #用正则表达式取出最里括号的内容, and remove 2-side brackets to get a new Expression: Content content = Re.search (' \ ([[\+\-\*\/]*\d+\.*\d*] {2,}\) ', expr). Group () #只取字符串中第1个到倒数第二个之间的内容, take the brackets off the sides. such as "(2+3)" Only take 2+3, do not take both sides of the brackets new_content = content[1:len (content)-1] # #将expr按匹配的内容进行分割: Get--before, match content, after, Get contents on both sides of content and assign value to Before,after new_list = Re.split (' \ ([\+\-\*\/]*\d+\.*\d*) {2,}\) ', expr) before = new_list[0] A fter = new_list[2] #before, nothing,after = Re.split (' \ ([\+\-\*\/]*\d+\.*\d*) {2,}\) ', expr) #将new_content进行计算, computed res     Ult result = Compute (new_content) #将before +result+after stitching, get new_expr new_expr = "%s%s%s"% (before,result,after)     #最终返回, recursive execution Excute (new_expr) return Excute (new_expr) #主函数if __name__ = = "__main__": #将带计算的表达式中的所包含的空格先去掉, get an expression with no spaces STR1 = "4*3-10* (3*2-1*9/3) +10" No_Space_str = re.sub (' \s* ', ' ', str1) #执行括号处理函数, take out the inner expression of precedence calculation or processing ret = Excute (no_space_str) #inp = [ret,0] #然后对取出来的 The inner-layer expression is computed: Includes processing multiplication after processing plus minus final = COMPUTE (ret) #打印最终计算的值 print final# ""

  

Python-based 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.