Python写的计算器程序(主要目的在于熟悉下正则表达式)

import re
s = '1-2*((60-30-(-40/5)*(9-2*5/3-7/3*99/4*2998-10*568/14.3))+(-4*3)/16-3)'
s2 = 1-2*((60-30-(-40/5)*(9-2*5/3-7/3*99/4*2998-10*568/14.3))+(-4*3)/16-3)
def check(s):#字符检错,不合法就返回False
flag = True
s = re.sub(' ','',s)#去空格
if re.findall('[^\d+\-*/.()]',s):#检测出常规计算字符外的其他字符
print('存在非法字符')
flag = False
elif re.findall('(\.\d\.)|(\D\.\D)|(\d\.\D)|(\D\.\d)',s):#检查出错误的小数
print('存在小数格式异常')
flag = False
elif re.findall('[*/+\-]+[*/+\-]+|.[*/+\-]\)',s):#判断计算符号输入是否异常
print('计算符号有误')
flag = False
if flag == False:
s = None
return s

def jisuan1(string):
if re.findall('[()]',string):#有括号的处理方式
string = re.sub('[()]','',string)
while True:
string.replace('+-','-')
string.replace('-+', '-')
string.replace('--', '+')
try:
x = re.search('[\-]*(?:\d+\.\d*|\d*)[*/](?:\d+\.\d*|\d*)',string).group()
if '*' in x:
y = float(x[:x.index('*')]) * float(x[x.index('*')+1:])
string = string.replace(x,str(y))
else:
y = float(x[:x.index('/')]) / float(x[x.index('/') + 1:])
string = string.replace(x, str(y))
except :
try:
x = re.search('[\-]*(?:\d+\.\d*|\d+)[+\-](?:\d+\.\d*|\d+)', string).group()
if '+' in x:
y = float(x[:x.index('+')]) + float(x[x.index('+') + 1:])
string = string.replace(x, str(y))
else:
if x.count('-') >1:
y = float(''.join(['-',x.split('-')[1]])) + float(''.join(['-',x.split('-')[2]]))
string = string.replace(x, str(y))
else:
y = float(x[:x.index('-')]) - float(x[x.index('-') + 1:])
string = string.replace(x, str(y))
except Exception as e:
raise e
if re.findall('[\-]*(?:\d+\.\d*|\d+)[+\-*/](?:\d+\.\d*|\d+)',string) == []:
break
return string

def jisuan2(s):#获取括号里的内容,并加以计算
if s != None:
while True:
k = re.findall('(?:\d+\.\d*|\d+)[*/][\-+]+(?:\d+\.\d*|\d+)',s)
for j in k:
if '+' in j:
s = s.replace(j,j.replace('+',''))
else:
s = s.replace(j, ''.join(['-', j.replace('-', '')]))
s = s.replace('--', '+')
s = s.replace('+-', '-')
s = s.replace('-+', '-')
try:
x = re.search('\([^()]+\)',s).group()#得到最里层括号的内容
a = jisuan1(x) # 将内容计算出来
s = s.replace(x, a) # 将计算结果与之前的内容置换
except Exception as e:
a = jisuan1(s) # 将内容计算出来
s = a # 将计算结果与之前的内容置换
if re.findall('[\-]*(?:\d+\.\d*|\d+)[+\-*/](?:\d+\.\d*|\d+)', s) == []:
break
return s
#
a = check(s)
print('代码结果:',jisuan2(a))
print('正确结果:',s2)


转载于:https://www.cnblogs.com/jt925/p/9655842.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值