流程图:
Paste_Image.png
代码:
import re
def special_handles(formula):
""" 操作加减符号处理
:param expression:表达式
:return:计算结果 """
formula = formula.replace('+-','-')
formula = formula.replace('--', '+')
formula = formula.replace('-+', '-')
formula = formula.replace('++', '+')
return formula
def calculate(formula):
""" 操作加减乘除
:param expression:表达式
:return:计算结果 """
formula = formula.strip('()')
formula = special_handles(formula)
signs = re.findall('[+-]',formula)
melement = re.split('[+-]',formula)
if melement[0] == '':
melement[1]= '-%s'%melement[1]
del melement[0]
del signs[0]
for index,i in enumerate(melement):
if i.endswith('*') or i.endswith('/'):
melement[index] = i + '-%s'%melement[index+1]
del signs[index]
del melement[index+1]
for index,i in enumerate(melement):
sub_res =mult_div(i)
melement[index]=sub_res
res2 = None
for index,i in enumerate(melement):
if res2:
if signs[index-1] == '+':
res2 += float(i)
elif signs[index-1] == '-':
res2 -= float(i)
else:
res2 = float(i)
return res2
def mult_div(formula):
""" 操作乘除
:param expression:表达式
:return:计算结果 """
signs = re.findall('[*/]',formula)
element = re.split('[*/]',formula)
res = None
for index, i in enumerate(element):
if res:
if signs[index-1] == '*':
res *= float(i)
elif signs[index-1] == '/':
res /= float(i)
else:
res = float(i)
return res
def calculator(formula):
""" 操作计算简易公式
:param expression:表达式
:return:计算结果 """
formula = re.sub('\s+','',formula)
final_outcome = None
flag = False
count = 1
while not flag:
brackets = re.search('\([^()]+\)', formula)
if brackets:
brackets_outcome = calculate(brackets.group())
print('\033[41;1m第%d次\033[0m括号内\033[42;1m%s\033[0m计算结果:%d'%(count,brackets.group(),brackets_outcome))
count += 1
formula = formula.replace(brackets.group(),str(brackets_outcome))
else:
final_outcome = calculate(formula)
print('\n\n\033[42;1m最终结果:\033[0m%s'%final_outcome)
flag = True
res = calculator("1 - 2 * ( (60-30 +(-9-2-5-2*3-5/3-40*4/2-3/5+6*3) * (-9-2-5-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )")
Paste_Image.png
网友评论