标签:class div return val list ret for string not
import re
res=‘1 - 2 * ( (60-30 + (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 ) * (-40/5)) - (-4*3)/ (16-3*2) )‘
res=res.replace(‘ ‘,‘‘)
print(eval(res))
# print(re.findall(r‘-?[\d\.]+|\+|\-|\*|/‘, res))
def grep(list):
#过滤符号
list=list.replace("++","+")
list=list.replace(‘+-‘,‘-‘)
list=list.replace(‘-+‘,‘-‘)
list=list.replace(‘--‘,‘+‘)
return list
def jisuan(list,x):
#计算乘除
index=list.index(x)
if x==‘*‘:
num=float(list[index-1])*float(list[index+1])
else:
num=float(list[index-1])/float(list[index+1])
del list[index-1],list[index-1],list[index-1]
list.insert(index-1,str(num))
return list
def jisuan2(list):
#计算加减
index=list.index(‘+‘)
num = float(list[index - 1]) +float(list[index + 1])
del list[index - 1], list[index - 1], list[index - 1]
list.insert(index - 1, str(num))
return list
def pangduan(list):
#判断计算先后顺序
while 1:
if ‘*‘in list and ‘/‘not in list:
jisuan(list,‘*‘)
elif ‘/‘ in list and ‘*‘not in list:
jisuan(list,‘/‘)
elif ‘*‘in list and ‘/‘in list:
a=list.index(‘*‘)
b=list.index(‘/‘)
if a>b:
jisuan(list,‘*‘)
else:
jisuan(list,‘/‘)
elif ‘+‘in list:
jisuan2(list)
else:
num = 0
for i in list:
num+=float(i)
return num
def zhaokuohao(string):
#寻找所有里层括号,和括号并计算结果
res1=re.search(‘\([^()]+\)‘,string)
if res1:
kuohao=res1.group()
mylist=re.findall(r‘-?[\d\.]+|\+|\-|\*|/‘, res1.group())
x=pangduan(mylist)
string=string.replace(kuohao,str(x))
# print(x)
string=grep(string)
# print(string)
return zhaokuohao(string)
else:
# print(string)
return string
def end(string):
#处理剩下无括号的外层
b=re.findall(r‘-?[\d\.]+|\+|\-|\*|/‘,string)
print(pangduan(b))
end(zhaokuohao(res))
end(zhaokuohao(‘1+1‘))
标签:class div return val list ret for string not
原文地址:http://www.cnblogs.com/fyknight/p/6791536.html