File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -38,6 +38,27 @@ def multiply(x, y):
3838 return result
3939
4040
41+ def split_exp (exp_str ):
42+ """
43+ 分解运算表达式
44+ """
45+ r_list = []
46+ t_list = []
47+ for i in exp_str :
48+ if i .isdigit () or i == '.' :
49+ t_list .append (i )
50+ elif t_list :
51+ r_list .append ('' .join (t_list ))
52+ t_list = []
53+ r_list .append (i )
54+ else :
55+ r_list .append (i )
56+ if t_list :
57+ r_list .append ('' .join (t_list ))
58+ del t_list [:]
59+ return r_list
60+
61+
4162def get_reversed_polish (exp ):
4263 """
4364 获取逆波兰式
@@ -54,7 +75,7 @@ def get_reversed_polish(exp):
5475 r_list = []
5576 s_list = []
5677 for i in exp :
57- if i . isdigit () :
78+ if type ( eval ( i )) in [ int , float ] :
5879 r_list .append (i )
5980 if i in priority .keys ():
6081 if i == '(' or not s_list :
@@ -79,11 +100,12 @@ def get_reversed_polish(exp):
79100 return r_list
80101
81102
82- def expression ( exp ):
103+ def calculate_exp ( exp_str ):
83104 """
84105 计算表达式
85106 """
86- exp = get_reversed_polish (exp )
107+ exp_list = split_exp (exp_str ) # 分解表达式
108+ exp = get_reversed_polish (exp_list ) # 获取逆波兰式
87109 s_list = []
88110 for i in exp :
89111 if i .isdigit ():
@@ -110,15 +132,15 @@ def test_expression():
110132 表达式测试
111133 """
112134 exp_01 = '2+3*(5-2)'
113- print expression (exp_01 )
135+ print calculate_exp (exp_01 )
114136 print eval (exp_01 )
115137
116138 exp_02 = '2*(1+2/2)'
117- print expression (exp_02 )
139+ print calculate_exp (exp_02 )
118140 print eval (exp_02 )
119141
120142 exp_03 = '2*(1+2/2)*(1+2)'
121- print expression (exp_03 )
143+ print calculate_exp (exp_03 )
122144 print eval (exp_03 )
123145
124146
You can’t perform that action at this time.
0 commit comments