python,实现计算器程序,加减乘除混合运算加括号,完善实现作业:要求实现⼀个由键盘输⼊表达式,计算结果的⼩程序.
import re
#detect error input
s = input("Expression:")
s = re.sub('\s',"",s)
if re.findall('[^0-9\+\-\*/\)\(]',s):
print("Error input,Stop!")
exit()
def judge1(sign):
if sign == '*':
obj = repile('\*')
elif sign == '/':
obj = repile('/')
return(obj)
def judge2(sign):
if sign == '+':
obj = repile('\+')
elif sign == '-':
obj = repile('\-')
return(obj)
def Format(s):
s = s.replace('','')
s = s.replace('++','+')
s = s.replace('+-','-')
s = s.replace('-+','-')
s = s.replace('--','+')
return(s)
def calculate(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)
def first_step(s):
while re.search('\([^()]+\)',s):
res = re.search('\([^()]+\)',s)
s_temp = up()
print(s_temp)
[first,second] = s.split(s_temp)
ret = re.search('\([^()]+\)',s)
tmp = re.search('[^()]+',up())
up())
temp = str(up()))
print('temp=',temp)
s = first + temp + second
print('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)
花了两天时间终于完成这个⼩作业了,其实没什么难度,就是正则表达式的灵活运⽤,由于逻辑⽐较复杂,测试花费了很多时间.
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论