标签:res 去掉 else get bsp strip logs class enum
看兄弟连的Alex视频提到一题作业:计算字符串 "1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"()不可以用eval)
我试了下,实现思路可能稍微有点复杂,不过代码不是很复杂,仅做参考。
import re def get_parentheses(s): s = s.replace(‘ ‘,‘‘) #空格去掉 #print(s) #print("====================") while True: L = re.findall("\([+\-\*/\d\.]+\)", s) #找到所有最内层的括号 if L: for i in L: tmp = i.strip(‘()‘) result = get_multiplicative_division(tmp) s = s.replace(i,result) s = s.replace(‘+-‘,‘-‘) s = s.replace(‘--‘,‘+‘) # print(s) # print("====================") else: s = get_multiplicative_division(s) break return s """ get_multiplicative_division函数用来计算无括号的表达式,实现思路应该能理解 """ def get_multiplicative_division(s): num_list = re.findall(‘[\-]?[\d\.]+‘,s) sign_list = re.findall(‘[+\*/]‘,s) for i, s in enumerate(num_list): if ‘-‘ in s and i >0 and len(sign_list)<len(num_list)-1: sign_list.insert(i - 1,‘+‘) for i, s in enumerate(sign_list): if s ==‘*‘ : num_list[i+1] = float(num_list[i]) * float(num_list[i+1]) num_list[i] = 0 elif s == ‘/‘: num_list[i+1] = float(num_list[i]) / float(num_list[i+1]) num_list[i] = 0 else: continue result = 0 for i in num_list: result += float(i) return str(result) if __name__ == ‘__main‘: s = "1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )" print(get_parentheses(s))
其实,个人觉得实现方法很多,只是实现思路不同而已。
标签:res 去掉 else get bsp strip logs class enum
原文地址:http://www.cnblogs.com/xjw-gjq/p/7135892.html