import re
def main():
#""代表的是空,split()方法已空格或者\t,\n进行切割,join方法是列表,元组,字典变为字符串
a = "".join("1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + \
7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )".split())
while True:
if '(' in a: #只要有括号就循环
ct = re.search(r'[(]([^()]+[)])',a) #查找()的内容,[^()]非括号的内容,所以刚开始只能(-40/5)
print(ct)
if ct is not None:
b = ct.group()
print(b)
c = count(b) #放到计算式进行计算
a = re.sub(r'[(]([^()]+[)])',str(c),a,1) #括号内的内容进行替换
print(a)
else:
c = count(a)
print(c)
break
def add_min(a):
"""
计算加减法
:param a:
:return:
"""
if "--" in a:
a = a.replace('--','+')
c = re.findall(r'-?\d+\.?\d*',a)
ls = []
for i in c:
ls.append(float(i))
rest = sum(ls) #sum函数可以对负数进行处理
return rest
def mul(a):
"""
计算乘法
:param a:
:return: a
"""
b = re.search(r'\d+\.?\d*(\*-?\d+\.?\d*)',a).group()
print(b)
if b is not None:
rest = 1
c = re.findall(r'-?\d+\.?\d*',b)
ls = []
for item in c:
ls.append(float(item))
for i1 in range(len(ls)):
rest = rest * ls[i1]
a = re.sub(r'\d+\.?\d*(\*-?\d+\.?\d*)+',str(rest),a,1)
return a
def div(a):
"""
计算除法
:param a:
:return:
"""
b = re.search(r'\d+\.?\d*(\/-?\d+\.?\d*)+',a)
if b is not None:
b = b.group()
print(b)
c = re.findall(r'-?\d+\.?\d*',b)
ls = []
for i in c:
ls.append(float(i))
rest = ls[0]
for i1 in range(1,len(ls)):
rest = rest / ls[i1]
a = re.sub(r'\d+\.?\d*(\/-?\d+\.?\d*)+',str(rest),a,1) #此处负号没有匹配,负号进行了保留
return a
def count(b):
"""
根据不同符号,调用不同的计算公式,计算出结构
:param b:
:return:
"""
while True: #while循环,只有遇到break和return才会结束循环
if '*' in b: #while循环,只要if语句成立,if结束之后就会重头开始循环,这就是while语句
c = b.split('*')
print(c)
if '/' in c[0]:
b = div(b) #b得到返回值,就再次进行以上的匹配
else:
b = mul(b)
elif '/' in b:
b = div(b)
elif '+' or '-' in b:
b = add_min(b)
return b
else:
return b
main()