计算加减乘除混合运算python实现_python,实现计算器程序,加减乘除混合运算加括号,完善实现...
importre#detect error input
s = input("Expression:")
s= re.sub('\s',"",s)if re.findall('[^0-9\+\-\*/\)\(]',s):print("Error input,Stop!")
exit()defjudge1(sign):if sign == '*':
obj= re.compile('\*')elif sign == '/':
obj= re.compile('/')return(obj)defjudge2(sign):if sign == '+':
obj= re.compile('\+')elif sign == '-':
obj= re.compile('\-')return(obj)defFormat(s):
s= s.replace(' ','')
s= s.replace('++','+')
s= s.replace('+-','-')
s= s.replace('-+','-')
s= s.replace('--','+')return(s)defcalculate(s):while re.search('[\*,/]',s):
s=Format(s)
obj= judge1(re.search('[\*,/]',s).group())
res=obj.split(s)
first= re.search('[\d,\.]+$',res[0]).group()
second= re.search('^[\d,\.,\-]+',res[1]).group()if re.search('\.',first):
fir=float(first)else:
fir=int(first)if re.search('\.',second):
sec=float(second)else:
sec=int(second)if re.search('[\*,/]',s).group() == '*':
result= str((fir *sec))
s= re.sub('%s\*%s'%(first,second),result,s)print('s=',s)elif re.search('[\*,/]',s).group() == '/':
result= str(fir /sec)
s= re.sub('%s/%s'%(first,second),result,s)print('s=',s)if re.search('^\-[\d,\.]+',s):return(s)
s=Format(s)#return(s)
while re.search('[\+,\-]',s):
s=Format(s)
obj= judge2(re.search('[\+,\-]',s).group())
res=obj.split(s)
first= re.search('[\d,\.]+$',res[0]).group()
second= re.search('^[\d,\.,\-]+',res[1]).group()if re.search('\.',first):
fir=float(first)else:
fir=int(first)if re.search('\.',second):
sec=float(second)else:
sec=int(second)if re.search('[\+,\-]',s).group() == '+':
result= str(fir +sec)
s= re.sub('%s\+*%s'%(first,second),result,s)print('s=',s)elif re.search('[\+,\-]',s).group() == '-':
result= str(fir -sec)
s= re.sub('%s\-%s'%(first,second),result,s)print('=',s)if re.search('^\-[\d,\.]+',s):return(s)
s=Format(s)return(s)deffirst_step(s):while re.search('\([^()]+\)',s):
res= re.search('\([^()]+\)',s)
s_temp=res.group()print(s_temp)
[first,second]=s.split(s_temp)
ret= re.search('\([^()]+\)',s)
tmp= re.search('[^()]+',ret.group())print(tmp.group())
temp=str(calculate(tmp.group()))print('temp=',temp)
s= first + temp +secondprint('first=',first)print('second=',second)print('temp=',temp)print('new s=',s)#if re.search('[\+,\-]{1}',s):#break
result =calculate(s)print("result=",result)
first_step(s)
花了两天时间终于完成这个小作业了,其实没什么难度,就是正则表达式的灵活运用,由于逻辑比较复杂,测试花费了很多时间.