标签:ase not int 计算 turn 计算器 字符串 ret inpu
import re
num =input(‘please input your equation:‘).strip()
num =num.replace(‘ ‘,‘‘)
def add(s): #计算加减,s是字符串,如s=‘4+5-4‘
add_num =f(s)
add_num =add_num.split(‘+‘)
sum = 0
sum_1 = 0
for i in add_num:
if ‘-‘ in i:
s2 = i.split(‘-‘)
for i in s2:
if i:
sum_1 = sum_1-float(i)
if s2[0]:
sum_1=float(s2[0])*2+sum_1
else:
sum += float(i)
sum = sum + sum_1
return str(sum)
def muldiv(s):#进行乘除
if not re.search(‘\d+\.?\d*[*/]-?\d+\.?\d*‘,s):
return s
res =re.search(‘\d+\.?\d*[*/]-?\d+\.?\d*‘,s)
res =res.group()
if ‘*‘in res:
a,b=res.split(‘*‘)
res_num =float(a)*float(b)
else:
a,b=res.split(‘/‘)
res_num =float(a)/float(b)
s =s.replace(res,str(res_num))
return muldiv(s)
def f(s): #把‘+-‘变成‘-‘
res=s.replace(‘+-‘,‘-‘)
res=res.replace(‘--‘,‘+‘)
return res
while re.search(‘\([^()]+\)‘,num):
res = re.search(‘\([^()]+\)‘, num)
res1 = res.group()
res =res1[1:-1]
res_num = muldiv(res) # 把乘除进行计算了
res_num = add(res_num) # 把加减进行计算了
num =num.replace(res1, res_num)
else:
res_num =muldiv(num)
res_num =float(add(res_num))
print(‘%.2f‘%res_num)
标签:ase not int 计算 turn 计算器 字符串 ret inpu
原文地址:http://www.cnblogs.com/IQ-Python/p/6784413.html