import re
s = '2-1*-22-3-4/-5'
def result_small( s ): # 计算乘除
if '*' in s:
a, b = s.split('*')
return float(a)*float(b)
elif '/' in s:
a, b = s.split('/')
return float(a)/float(b)
def get_small( s ): #获取乘除最小单位
while True:
ret = re.search(r'\d+(\.\d+)?[*/]-?\d+(\.\d+)?', s)
if ret:
res = result_small(ret.group())
s = s.replace(ret.group(), str(res))
else:
break
return s
def get_change(s): #修正符号
s = s.replace("--", '+')
s = s.replace('+-', '-')
s = s.replace('-+', '-')
s = s.replace('++', '+')
return s
def add_sub(s): # 求和
ret = re.findall(r'[+-]?\d+(?:\.\d+)?', s)
sum = 0
for i in ret:
sum = sum + float(i)
return sum
def main(s): #计算
s = s.replace(' ', '')
s = get_small(s)
s = get_change(s)
s = add_sub(s)
return s
def content(s):
s = s.replace(' ', '')
while True:
ret = re.search(r'\([^()]+\)', s)
if ret:
reg = str(main(ret.group()))
print(ret.group(), main(ret.group()))
s = s.replace(ret.group(), reg)
s = get_change(s)
else:
break
return main(s)
ret = content("1 - 2 * ( (60 - 30 +(-40/ 5) * (9-2 * 5/ 3 + 7 / 3 * 99/ 4 * 2998 + 10 * 568/14 )) - (-4 * 3)/ (16-3*2) )")
print(ret)
print(eval('1 - 2 * ( (60 - 30 +(-40/ 5) * (9-2 * 5/ 3 + 7 / 3 * 99/ 4 * 2998 + 10 * 568/14 )) - (-4 * 3)/ (16-3*2) )'))
# 先正则匹配到最内层括号,然后计算结果并替换直到没有括号,然后计算乘除,最后计算加减