使用python实现计算器功能


学习python过程中的作业。实现了+、-、×、/、及幂运算,支持括号优先级。

代码为python3.5

  1 import re
  2 def formatEquation(string):
  3     string = string.replace("--", "+")
  4     string = string.replace("-+", "-")
  5     string = string.replace("++", "+")
  6     string = string.replace("+-", "-")
  7     string = string.replace("*+", "*")
  8     string = string.replace("/+", "/")
  9     string = string.replace(' ', '')
 10     return string
 11 def findErrorChar(equation):
 12     '''
 13     查找非计算的字符
 14     '''
 15     re_rule = r"[^ \.\d\+\-\*\/\(\)]+"
 16     req = re.findall(re_rule,equation)
 17     return req
 18 def findErrorOperator(equation):
 19     '''
 20     查找连续多次出现的运算符号
 21     '''
 22     re_rule = r'[+\-/*][+\-/*][+\-/*]*'
 23     req = re.findall(re_rule,equation)
 24     while '**' in req:
 25         req.remove('**')    
 26     return req
 27 def addSubtract(equation):
 28     '''
 29     加减法运算,递归运算
 30     '''
 31     re_rule = r'[-]?\d+\.?\d*[+-]\d+\.?\d*'
 32     if re.search(re_rule,equation):
 33         req = re.search(re_rule,equation).group()
 34         if '+' in req:
 35             x,y = req.split('+')
 36             string = str(float(x) + float(y)) 
 37             equation = formatEquation(equation.replace(req,string))
 38             return addSubtract(equation)
 39         if '-' in req:
 40             if req.startswith('-'):
 41                 req1 = req[1:]
 42                 x,y = req1.split('-')
 43                 x = '-'+x
 44             else:
 45                 x,y = req.split('-')
 46             string = str(float(x) - float(y)) 
 47             equation = formatEquation(equation.replace(req,string))
 48             return addSubtract(equation)
 49     else:
 50         return equation
 51 
 52 def multiplicationDivision(equation):
 53     '''
 54     乘除法及幂运算,递归运算
 55     '''
 56     re_rule = r'\d+\.?\d*([*/]|\*\*)[\-]?\d+\.?\d*'
 57     print(11)
 58     if re.search(re_rule,equation):
 59         req = re.search(re_rule,equation).group()
 60         print(req)
 61         if '**' in req:
 62             x,y = req.split('**')
 63             string = str(float(x) ** float(y)) 
 64             equation = formatEquation(equation.replace(req,string))
 65             return multiplicationDivision(equation)
 66         if '*' in req:
 67             x,y = req.split('*')
 68             string = str(float(x) * float(y)) 
 69             equation = formatEquation(equation.replace(req,string))
 70             return multiplicationDivision(equation)
 71         if '/' in req:
 72             x,y = req.split('/')
 73             string = str(float(x) / float(y)) 
 74             equation = formatEquation(equation.replace(req,string))
 75             return multiplicationDivision(equation)
 76     else:
 77         return equation
 78 def removeBrackets(equation):
 79     '''
 80     计算算式中括号里的公式,直到所有括号的计算已完成
 81     '''
 82     re_rule =  r'\([^()]*\)'
 83     equation = formatEquation(equation)
 84     if re.search(re_rule,equation):
 85         req = re.search(re_rule,equation).group()
 86         string = addSubtract(multiplicationDivision(req[1:-1]))
 87         equation = equation.replace(req,string)
 88         return removeBrackets(equation)
 89     else:
 90         return equation
 91 if __name__ == '__main__':
 92     while 1:
 93         #equation = input("请输入需要计算的公式")
 94         equation = "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) )"
 95         equation = equation.replace(' ','')
 96         #判断字符是否合法
 97         if findErrorChar(equation) :
 98             errorChar = findErrorChar(equation)
 99             print("下列字符不合法:",''.join(errorChar))
100         elif findErrorOperator(equation):
101             errorOperator = findErrorOperator(equation)
102             print("下列字符不合法:",''.join(errorOperator))
103         else:
104             #格式化算式
105             formatEquation(equation)
106             print("输入的公式为:",equation)
107             #去除括号
108             equation = removeBrackets(equation)
109             #计算结果
110             equation = addSubtract(multiplicationDivision(equation))
111             print('程序计算结果为:',equation)
112             print('eval计算结果为:',eval(equation))
113             break
源代码

优质内容筛选与推荐>>
1、面向对象之类属性实例属性及其增删改查
2、C#枚举类型的使用示例
3、26 October in 614
4、linux 文件&文件夹大小排序
5、javadoc注释规范


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn