欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-08-21 22:48:32
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): ......
python 实现计算器功能 输入字符串,输出相应结果
 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