# python用re模块实现数学公式计算

2019/03/21 15:58

2.算到中间部，可能有*-， +- ，-- ，这样的情况

import re

'''计算字符串表达式'''
bracket = re.compile('$$[^()]+$$')  # 查找最内层括号
div = re.compile('(\d+\.?\d*/-\d+\.?\d*)|(\d+\.?\d*/\d+\.?\d*)')  # 查找除法运算
mul = re.compile('(\d+\.?\d*\*-\d+\.?\d*)|(\d+\.?\d*\*\d+\.?\d*)')  # 查找乘法运算
sub = re.compile('(-\d+\.?\d*-\d+\.?\d*)|(\d+\.?\d*-\d+\.?\d*)')  # 查找减法运算
c_f=re.compile('$$?\d+$$?')
strip=re.compile('[^()]')

def Div(s):
exp = re.split('/', div.search(s).group())
return s.replace(div.search(s).group(), str(float(exp[0]) / float(exp[1])))

def Mul(s):
exp = re.split('\*', mul.search(s).group())
return s.replace(mul.search(s).group(), str(float(exp[0]) * float(exp[1])))

def Sub(s):
exp = sub.search(s).group()
if exp.startswith('-'):
exp = exp.replace('-', '+')
exp = exp.replace('+', '', 1)
return s.replace(sub.search(s).group(), '-' + res)

else:
exp = re.split('-', sub.search(s).group())
return s.replace(sub.search(s).group(), str(float(exp[0]) - float(exp[1])))

def calc():
while True:
s = input('请输入等式').replace(' ','')
if s=='quit':
break
else:
while bracket.search(s):
s_search=bracket.search(s).group()
if div.search(s_search):
s=s.replace(s_search,Div(s_search))
elif mul.search(s_search):
s=s.replace(s_search,Mul(s_search))
elif sub.search(s_search):
s = s.replace(s_search, Sub(s_search))
elif c_f.search(s_search):
s=s.replace(s_search,strip.search(s_search).group())
print(s)

calc()

0
0 收藏

0 评论
0 收藏
0