python 求值表达式解析

时间:2023-03-09 20:22:25
python 求值表达式解析

采用中缀转后缀的算法。

注意我输入的格式。

#注意格式
def suffix(st):
listopt=[" "]
listnum=[" "] for i in range(0,len(st)):
if(differ(st[i])==1): #判断,对运算符操作
if(len(listopt)):
if(dictopt[st[i]] > dictopt[listopt[len(listopt)-1]]):#优先级比栈顶高,入栈
if st[i]==")":
while(1):
tmp=listopt.pop()
if tmp=="(":
break
else:
listnum.append(tmp)
listnum.append(" ")
else:
listopt.append(st[i]) else: #如果st[i]优先级比栈顶低,opt栈中依次放到num中,然后再把st[i]入opt栈
if st[i]=="(": #优先级低于栈顶元素的,可能是 加减乘除,也可能是"("。如果碰到 "("则 直接入栈
listopt.append(st[i])
else:
while(dictopt[st[i]]<dictopt[listopt[len(listopt)-1]] and len(listopt)!=0):#碰到的是 加减乘除
tmp=listopt.pop()
listnum.append(tmp)
listnum.append(" ") #运算符之间加空格,否则print cnt_string:“ 1.2 5 6 ** 57 14 - + ”
listopt.append(st[i])
else: #非运算符的操作,依次入num栈
listnum.append(st[i])
while(len(listopt)): #opt栈 依次放到 num栈
listnum.append(" ") #运算符前面加空格,否则print cnt_string:“ 1.2 5 6 * * 57 14-+ ”
listnum.append(listopt.pop())
return listnum #判断是运算符还是操作数:
def differ(elem):
if elem=="+" or elem=="-" or elem=="*" or elem=="/" or elem=="(" or elem==")":
return 1
else:
return 0
#整理字符串,列表,去除不必要的空格:
def order(st):
suffix_list=[]
tmp_list=suffix(st)
#print suffix_list
last_string="".join(tmp_list)
#print last_string
cnt_string=last_string.replace(" "," ")
#print cnt_string
cnt_string=cnt_string[1:len(cnt_string)-1] #空格去头去尾
cnt_list_tmp=cnt_string.split(" ")
for i in cnt_list_tmp:
if i!="":
suffix_list.append(i)
print suffix_list
return suffix_list #实现类似switch-case 功能:
def calc(type,x,y):
calculation = {"+":lambda x,y:( eval(x) + eval(y)),
"*":lambda x,y:( eval(x) * eval(y)),
"-":lambda x,y:( eval(x) - eval(y)),
"/":lambda x,y:( eval(x) / eval(y))
}
return calculation[type](x,y) #usage :result1 = calc('+',3,6) #计算:
def count(suffix_list):
tmp_list=[]
for i in suffix_list:
if not differ(i):
tmp_list.append(i)
else:
tmp1=tmp_list.pop()
tmp2=tmp_list.pop()
tmp3=calc(i,str(tmp2),str(tmp1))
tmp_list.append(tmp3)
return tmp_list[0] #main
dictopt={"+":1,"-":1,"*":2,"/":2," ":0,"(":-1,")":9} #优先级
st="1.2 - ( 5 * 6 + 7 + 8 ) * 4"#待求表达式
suffix_list=order(st)
answer=count(suffix_list)
print answer