计算器的实现:
#codeing:UTF-8 #__author__:Administrator #date:2018/4/9/009 20:26 source_str = "1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )" # source_str = "1 - 2 " # source_str = "1 - 2 * ( 60-30 +(-40/5) )" import re def check_source(source): FLAG = True if not source.count("(") == source.count(")"): print("Invalid") if re.findall('[a-z]',source.lower()): print("Invalid")#有病的, FLAG = False return FLAG def formate_source(source): source = source.replace(" ","") source = source.replace("++","+") source = source.replace("+-","-") source = source.replace("*+","*") source = source.replace("-+","-") source = source.replace("--","+") source = source.replace("/+","/") source = source.replace("//","/") return source def cal_mul_div(source): regular = '[-]?d+.?d*[/*][-]?d+.?d*' while re.search(regular,source): expression = re.search(regular,source).group() if expression.count("*")==1: x, y = expression.split("*") mul_result = "+"+str(float(x)*float(y)) source = source.replace(expression,mul_result) source = formate_source(source) if expression.count("/")==1: x, y = expression.split("/") mul_result = "+"+str(float(x)/float(y)) source = source.replace(expression,mul_result) source = formate_source(source) # print(source) return source def cal_add_sub(source): add_regular = '[-]?d+.?d*+[-]?d+.?d*' sub_regular = '[-]?d+.?d*-[-]?d+.?d*' # print(re.findall(add_regular,source))######### while re.findall(add_regular,source):#+ add_list = re.findall(add_regular,source) # print(add_list) for add_str in add_list: x,y = add_str.split("+") mul_result = "+"+str(float(x) + float(y)) source = source.replace(add_str, mul_result) source = formate_source(source) while re.findall(sub_regular,source):#- sub_list = re.findall(sub_regular,source) for sub_str in sub_list: x,y = sub_str.split("-") mul_result = "+"+str(float(x) - float(y)) source = source.replace(sub_str, mul_result) source = formate_source(source) return source if check_source(source_str): print("source:",source_str) print("eval result:",eval(source_str)) source = formate_source(source_str) print("formate source:",source) while re.search("(",source): deal_str = re.search("([^()]+)",source).group() # print(deal_str)# replace_str = cal_mul_div(deal_str) # print(replace_str)# replace_str = cal_add_sub(replace_str)#### # print(replace_str[1:-1]) source = formate_source(source.replace(deal_str,replace_str[1:-1])) # print(source) else: replace_str = cal_mul_div(source) replace_str = cal_add_sub(replace_str) # print(replace_str[1:-1]) source = formate_source(source.replace(source, replace_str[1:-1])) print("my result :",source)
测试结果: