作业需求:
1.实现加减乘除及拓号优先级解析
2.用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-25/3 + 7 /399/42998 +10 * 568/14 )) - (-43)/ (16-32) )等类似公式后,必须自己解析里面的(),+,-,,/符号和公式(不能调用eval等类似功能偷懒实现),运算后得出结果,结果必须与真实的计算器所得出的结果一致
作业思路
先把输入转成字符串,然后获取到最内层括号内的数据,根据运算优先级,从左到右先计算最内层括号内的运算,先乘除在加减,在循环,直到最内层括号内数据计算完,再从左到右计算次内层的括号,直到括号全部计算完,最后先乘除,最后加减,计算最终结果。
流程图
1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 # Author:Ahappier
4
5 import re
6
7
8 def main():
9 a=input("请输入需要计算的公式:")
10 b = "".join(a.split())
11 while True:
12 if "("in b:
13 c = re.search(r"\([^()]+\)",b)
14 if c is not None:
15 e=c.group()
16 d=cal(e)
17 b=re.sub(r"\([^()]+\)",str(d),b,1)
18 else:
19 c=cal(b)
20 print(c)
21 break
22
23 #addition and subtraction
24 def add_sub(b):
25
26 if "--" in b:
27 b=b.replace("--","+")
28 add_list = re.findall(r"-?\d+\.?\d*", b)
29 list=[]
30 for i in add_list:
31 list.append(float(i))
32 t=sum(list)
33 return t
34
35 #multiplication
36 def mul(b):
37 mul_ch=re.search(r"\d+\.?\d*(\*-?\d+\.?\d*)",b)
38 if mul_ch is not None:
39 mul_ch=mul_ch.group()
40 mul_list=re.findall(r"-?\d+\.?\d*",mul_ch)
41 list=[]
42 for i in mul_list:
43 list.append(float(i))
44 multip=list[0]*list[1]
45 b=re.sub(r"\d+\.?\d*(\*-?\d+\.?\d*)",str(multip),b,1)
46 return b
47
48 #division
49 def div(b):
50 div_ch=re.search(r"\d+\.?\d*(\/-?\d+\.?\d*)",b)
51 if div_ch is not None:
52 div_ch=div_ch.group()
53 div_list=re.findall(r"-?\d+\.?\d*",div_ch)
54 list=[]
55 for i in div_list:
56 list.append(float(i))
57 division=list[0]/list[1]
58 b=re.sub(r"\d+\.?\d*(\/-?\d+\.?\d*)",str(division),b,1)
59 return b
60
61 #calculation
62 def cal(c):
63 while True:
64 if "*"in c:
65 s=c.split("*")
66 if "/"in s[0]:
67 c=div(c)
68 else:
69 c=mul(c)
70 elif "/"in c:
71 c=div(c)
72 elif "+"or "-" in c:
73 c=add_sub(c)
74 return c
75 else:
76 return c
77
78 main()
View Code