码迷,mamicode.com
首页 > 其他好文 > 详细

s12-day04-work01 简单计算器功能实现

时间:2016-01-29 11:43:43      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

代码:

技术分享
 1 #!/usr/local/env python3
 2 ‘‘‘
 3 Author:@南非波波
 4 Blog:http://www.cnblogs.com/songqingbo/
 5 E-mail:qingbo.song@gmail.com
 6 ‘‘‘
 7 
 8 import time,sys
 9 import module
10 
11 if __name__ == "__main__":
12     while True:
13         count = 0
14         if count < 3:
15             print(‘‘‘
16             请输入一个计算公式,类似下面格式:
17             =========================================================================================
18             1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
19             =========================================================================================
20             系统默认匹配所有的数字、(、)、+、-、/、*、.
21                                                                                 计算器程序研发@南非波波
22             ‘‘‘)
23             expression = input("请输入:").strip()  #或取用户输入的表达式字符串,并去除左右的空格
24             # expression = "1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"
25             expression = expression.replace( ,‘‘) #去除字符串中间的空格,使用replace进行空字符串替换空格
26             if module.num_operator(expression): #成功匹配正确表达式
27                 # print(expression)
28                 result = module.recursion_bracket(expression) #将处理后没有括号的表达式赋值给expression
29                 print(result)
30                 break
31             else:
32                 count += 1
33                 print("你输入的表达式格式不正确!")
34                 time.sleep(1)
35                 continue
36         else:
37             print("你的输入错误次数已达三次,计算器将自动退出!感谢你的使用!")
38             time.sleep(1)
39             sys.exit(3)
index.py

 

技术分享
  1 #!/usr/local/env python3
  2 ‘‘‘
  3 Author:@南非波波
  4 Blog:http://www.cnblogs.com/songqingbo/
  5 E-mail:qingbo.song@gmail.com
  6 ‘‘‘
  7 
  8 import re
  9 
 10 #匹配一个表达式中的数字和运算符,如果匹配,返回expression,否则返回None
 11 def num_operator(expression):
 12     match_list = re.findall("[0-9]|\(|\)|\+|\-|\*|\/|.",expression)
 13     if len(expression) == len(match_list):
 14         return True
 15 
 16 #特殊字符处理
 17 def charmap(expression):
 18     flag = True
 19     while flag:
 20         if expression.__contains__("++") or expression.__contains__("+-") or expression.__contains__("-+") or expression.__contains__("--"):
 21             # match_str = re.search("\d+\.*\d*(\+\-){1}\d+\.*\d*",expression).group()
 22             expression = expression.replace(+-,-)
 23             expression = expression.replace(++,+)
 24             expression = expression.replace(-+,-)
 25             expression = expression.replace(--,+)
 26         else:
 27             flag = False
 28     return expression
 29 #操作加减
 30 def compute_add_sub(expression):
 31     ‘‘‘
 32     expression表达式传进来的形式是(5+1-4),左右成一对括号。所以这里需要将括号去掉
 33     ‘‘‘
 34     expression = expression.lstrip(().rstrip()) #去除表达式左右的括号
 35     match_test = re.search("\d+\.*\d*[\+\-]{1}\d+\.*\d*",expression)
 36     if not match_test:
 37         return expression
 38     else:
 39         match_str = match_test.group()
 40         if len(match_str.split(+)) > 1:
 41             num1,num2 = match_str.split("+")
 42             result = float(num1) + float(num2)
 43         else:
 44             num1,num2 = match_str.split("-")
 45             result = float(num1) - float(num2)
 46         exp_join = expression.split(match_str)
 47         expression = "%s%s%s" % (exp_join[0],result,exp_join[1])
 48     return compute_add_sub(expression)
 49 
 50 #操作乘除
 51 def compute_mul_div(expression):
 52     ‘‘‘
 53     expression表达式传进来的形式是(9-2*5/3+7/3*99/4*2998+10*568/14),左右成一对的括号。所以这里就需要将括号去掉然后递归处理乘除
 54     ‘‘‘
 55     expression = expression.lstrip(().rstrip()) #去除表达式左右的括号
 56     match_test = re.search("\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*",expression)
 57     if not match_test: #判断是否能够匹配到* 或者 /。
 58         return expression
 59     else:
 60         match_str = match_test.group() #获取到匹配的运算式,比如5/3,2*5
 61         if len(match_str.split("/")) > 1: #计算除法
 62             num1,num2 = match_str.split("/")
 63             result = float(num1) / float(num2)
 64         else: #计算乘法 len(match_str.split("*")) > 1
 65             num1,num2 = match_str.split("*")
 66             result = float(num1) * float(num2)
 67         exp_join = expression.split(match_str)
 68         expression = "%s%s%s" % (exp_join[0],result,exp_join[1])
 69         compute_mul_div(expression)  #递归处理
 70     return compute_mul_div(expression)
 71 
 72 #处理优先级的执行
 73 def compute_pri(expression):
 74     expression = compute_mul_div(expression) #处理乘除
 75     expression = charmap(expression) #处理特殊字符
 76     expression = compute_add_sub(expression)  #处理加减
 77     return expression #返回一个值
 78 
 79 #递归处理括号
 80 def recursion_bracket(expression):
 81     match_list = re.findall("\(|\)",expression) #匹配括号,如果存在递归处理
 82     if not match_list:
 83         # print(expression)
 84         return compute_pri(expression)
 85     else:
 86         match_str = re.search("\([^()]*\)",expression) #匹配第一次出现的括号对
 87         if match_str:
 88             match_str = match_str.group()
 89             # print("match_str:",match_str)
 90             tmp = compute_pri(match_str)
 91             expression = "%s%s%s" % (expression.split(match_str)[0],tmp,expression.split(match_str)[1]) #字符串拼接
 92             # print("expression:",expression)
 93     return recursion_bracket(expression) #递归处理括号
 94 
 95 
 96 
 97 
 98 # expression = "(9-2*5/3+7/3*99/4*2998+10*568/14)"
 99 # res = compute_pri(expression)
100 # print(res)
101 #递归处理括号
102 # def recursion_bracket(expression):
103 #     match_list = re.findall("\(|\)",expression) #匹配括号,如果存在递归处理
104 #     if match_list:
105 #         tmp_list = [] #定义一个列表,存储左括号(
106 #         res = ‘‘
107 #         for i in range(0, len(expression)):
108 #             if expression[i] == "(":
109 #                 tmp_list.append(i) #获取括号出现的索引值列表
110 #                 print("tmp_list:",tmp_list)
111 #                 continue
112 #             if expression[i] == ")" and tmp_list:
113 #                 ts = expression[tmp_list[-1]: i+1]
114 #                 if len(ts) > len(res):
115 #                     # ts = compute_mul_div(ts)
116 #                     # print(ts)
117 #                     # ts = charmap(ts)
118 #                     # ts = compute_add_sub(ts)
119 #                     res = ts
120 #                     print(‘i:%s,ts:%s‘ % (i,ts))
121 #                 tmp_list.pop()
122 #                 print(tmp_list)
123 #         print("res:",res)
124 #         # return recursion_bracket(res)
125 #
126 #     else: #匹配括号失败,返回表达式,做后续处理
127 #         expression = compute_mul_div(expression)
128 #         expression = charmap(expression)
129 #         expression = compute_add_sub(expression)
module.py

 

github代码更新地址:https://github.com/swht/projects/tree/master/day04/计算器

s12-day04-work01 简单计算器功能实现

标签:

原文地址:http://www.cnblogs.com/songqingbo/p/5168125.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!