命名真是一件痛苦的事情。不多说了,上代码
#-*- coding:utf-8 -*-
import sys
#具体操作函数
def cal_add(a,o,b):
a = float(a)
b = float(b)
if b ==0 and o =="/":
print "除数为0,退出系统"
sys.exit()
opt = {
"+": a + b,
"-": a - b,
"*": a * b,
"/": a / b
}
return opt.get(o)
#计算的操作函数
def caculate(callist,opt=["*","/"]):
#print callist
for i in callist:
#print callist[i]
#if i == "*" or i == "/":
if i in opt:
i_index = callist.index(i)
#print i_index-1,i_index+1
callist[i_index-1:i_index+1+1] = [ cal_add(callist[i_index-1],i,callist[i_index+1]) ]
#print "*/:",callist
return caculate(callist)
else:
for i in callist:
if i == "+" or i == "-":
i_index = callist.index(i)
#print i_index-1,i_index+1
callist[i_index-1:i_index+1+1] = [ cal_add(callist[i_index-1],i,callist[i_index+1]) ]
#print "+-:",callist
return caculate(callist)
return callist
#优先级 进行计算
def fenli(calstr):
if len(calstr.strip()) == 0: print "未检测出您输入,重新输入.";sys.exit()
newstr = ''.join(calstr.strip().split())
str_list = [ ]
cur_str = ''
if not newstr[0].isdigit(): newstr = '0'+ newstr
#newstr = list(newstr)
for i in newstr:
if i.isdigit() or i == ".":
cur_str += i
else:
if len(cur_str.strip()) != 0:
str_list.extend([cur_str,i])
else:
str_list.append(i)
cur_str = ''
else:
str_list.append(cur_str)
return str_list
#检测输入是否包含括号,并计算
def if_kuohao(callist):
count = callist.count("(")
if '(' in callist:
left = check_kuohao_index(callist)-1
right= callist.index(')')
new_list = callist[left:right+1]
#print 'newlist:',caculate(new_list)
callist[left:right+1] = [caculate(new_list)[1]]
#print "calllist",callist
return if_kuohao(callist)
else:
return caculate(callist)
#最内层括号的位置
def check_kuohao_index(callist,value="("):
count = callist.count(value)
print "含有%s个小括号"%count
c_index = 0
for i in range(count):
c_index = callist.index(value,c_index)
#print c_index
c_index +=1
return c_index
if __name__ == "__main__":
st_shuru = '-1+2.0/((3* (4/1))-1)'
result = if_kuohao(fenli(st_shuru))[0]
print result