python 实现计算器功能 输入字符串,输出相应结…

2019-01-01 23:20:51来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

 1 import re
 2 formul='2*(1+2*6/3-2)+5+2*(1+6/2/3-2)'
 3 
 4 def addjian(func):
 5     digital = re.split('(\D)',func)
 6     for index in range(1,len(digital),2):
 7         if digital[index] == '+':
 8             digital[index + 1] = str(int(digital[index - 1]) + int(digital[index + 1]))
 9         elif digital[index] == '-':
10             digital[index + 1] = str(int(digital[index - 1]) - int(digital[index + 1]))
11 
12     return digital[-1]
13 def chengchu(func):
14     ret = re.findall('\d+[^+-]+\d',func)
15     for i in ret:
16         digital = re.split('(\D)',i)         #加个括号是为了优先级的原因,保留非数字
17         for index in range(1,len(digital),2):##这个地方的思想很巧妙,假设[1,/,2,*,3,/,4,*,5],
18                                                # 我会把1/2的结果替换到2的身上位0.5,然后,0.5*3的结果替换到3的身上,最终结果取最后一个。。。
19             if digital[index] == '*' :
20                 digital[index+1] = str(int(digital[index-1])*int(digital[index+1]))
21             elif digital[index] == '/' :
22                 digital[index + 1] = str(int(digital[index - 1]) //int(digital[index + 1]))
23         func = re.sub('\d+[^+-]+\d',digital[-1],func,1)
24     return func
25     print(ret)
26     a=1
27 
28 def comput(formal):
29     re.sub('\s','',formal)
30     while(not formal.isdigit()):
31         ret = re.findall('\(([^()]*)\)',formal)
32         print(ret)
33         if ret:
34             for i in ret:
35                 if '*'in i or '/' in i:
36                     result_chengchu = chengchu(i)#先算乘除
37                 else:
38                     result_chengchu = i
39                 if '+'in result_chengchu or '-' in result_chengchu:
40                     result_addjian = addjian(result_chengchu)#再算加减
41                 else:
42                     result_addjian = result_chengchu
43 
44                 formal = re.sub('\(([^()]*)\)',str(result_addjian),formal,1)
45         else:
46             if '*' in formal or '/' in formal:
47                 result_chengchu = chengchu(formal)  # 先算乘除
48             else:
49                 result_chengchu = formal
50             if '+' in result_chengchu or '-' in result_chengchu:
51                 result_addjian = addjian(result_chengchu)  # 再算加减
52             else:
53                 result_addjian = result_chengchu
54             formal = result_addjian
55     print(formal)
56 
57 comput(formul)
View Code

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python开发环境安装

下一篇:使用request实现手工输入验证码登录