Day15:The simple calculator

 1 import re
 2 
 3 def multifly_cha(s):
 4     ret = float(s.split("*")[0]) * float(s.split("*")[1]) if "*" in s else float(s.split("/")[0]) / float(s.split("/")[1])
 5     return ret
 6 
 7 def remove_cha(s):
 8     if "*" not in s and "/" not in s:
 9         return s
10     else:
11         k = re.search(r"-?[d.]+[*/]-?[d.]+",s).group()
12         s = s.replace(k,"+" + str(multifly_cha(k))) if re.findall(r"-",k) == 2 else s.replace(k, str(multifly_cha(k)))
13         return remove_cha(s)
14 
15 def add_up(s):
16     l = re.findall("([d.]+|-|+)", s)
17     if l[0] == "-":
18         l[0] = l[0] + l[1]
19         del l[1]
20     sum = float(l[0])
21     for i in range(1,len(l),2):
22         if l[i] == "+" and l[i+1] != "-":
23             sum += float(l[i+1])
24         elif l[i] == "+" and l[i + 1] == "-":
25             sum -= float(l[i + 2])
26         elif l[i] == "-" and l[i + 1] == "-":
27             sum += float(l[i + 2])
28         elif l[i] == "-" and l[i + 1] != "-":
29             sum -= float(l[i + 1])
30 
31     return sum
32 
33 def basic_operation(s):
34     s = s.replace(' ','')
35     return add_up(remove_cha(s))
36 
37 def calculate_(expression):
38     if not re.search(r"([^()]+)",expression):
39         return basic_operation(expression)
40     k = re.search(r"([^()]+)",expression).group()
41     expression = expression.replace(k,str(basic_operation(k[1:len(k)-1])))
42     return calculate_(expression)
43 
44 s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
45 print("the evals results is: {}
the calculate results is: {}".format(eval(s),calculate_(s)))
View Code
原文地址:https://www.cnblogs.com/zxver/p/12668888.html