设计思路:首先对输入的计算公式做格式化处理和非法输入检测(这里主要检测是否有小写字母),然后对有括号和无括号两种情况,通过re.search()方法匹配处理(特别注意匹配负数和小数的情况以及[\*]是不需要去特殊化处理的),当做乘除法计算时用re.split()方法取到数值,做加减法时则用re.findall()方法取到数值,最后用str.replace()方法逐步更新字符串中的运算式
#!/usr/bin/env Python
# coding=utf-8
import re
def check(s):
flag=True
if re.search('[a-z]',s):
print('invalid input')
flag=False
return flag
def format(s):
s = s.replace(' ', '')#替换所有空格为空
s = s.replace('--','+')
s = s.replace('+-','-')
return s
def count_chengchu(s):#45*25
x,y=re.split('[*/]',s)#将值赋给x和y
if re.search('\*',s):
s=float(x)*float(y)
else:
s=float(x)/float(y)
return s
def count_jiajian(s):#45+25=70
[x,y] = re.findall('-?\d+\.?\d*', s) # 将值赋给x和y
s=float(x)+float(y)
return s
exit_flag=False
while not exit_flag:
num = input('please input count_num[quit:Q]>>')
if num == 'Q':
print('thanks')
exit_flag=True
elif check(num):#无错误输入
count_end = False
while not count_end:
num=format(num)
if re.search('\([^()]+\)', num):#是否存在最里面的括号
count1 = re.search('\([^()]+\)', num).group() # 接收最里面的括号如(-7.0)
if re.search('-?\d+\.?\d*[/*]-?\d+\.?\d*', count1):
count2 = re.search('-?\d+\.?\d*[/*]-?\d+\.?\d*', count1).group() # 接收这个最高优先级的乘除法45*25
count3 = count_chengchu(count2)
num = num.replace(count2, str(count3))
elif re.search('-?\d+\.?\d*[-+]-?\d+\.?\d*', count1):
count2 = re.search('-?\d+\.?\d*[-+]-?\d+\.?\d*', count1).group() # 接收这个最高优先级的加减法45*25
count3 = count_jiajian(count2)#(-7)
num = num.replace(count2, str(count3))#-(-7.0)
else:#去括号
ret1 = re.search('-?\d+\.?\d*', count1).group() # 105
num = num.replace(count1, ret1)# 45-105
else:#45-2*3/3不存在括号
if re.search('-?\d+\.?\d*[/*]-?\d+\.?\d*', num):
count2 = re.search('-?\d+\.?\d*[/*]-?\d+\.?\d*', num).group() # 接收这个最高优先级的乘除法45*25
count3 = count_chengchu(count2)
num = num.replace(count2, str(count3))
elif re.search('-?\d+\.?\d*[-+]-?\d+\.?\d*', num):
count2 = re.search('-?\d+\.?\d*[-+]-?\d+\.?\d*', num).group() # 接收这个最高优先级的加减法45*25
count3 = count_jiajian(count2)
num = num.replace(count2, str(count3))
print(num)
count_end=True
---------------------
作者:Cristano1234
来源:CSDN
原文:https://blog.csdn.net/clr100/article/details/80494553
|
|