首页 > 代码库 > 运用正则表达式不使用内置方法实现计算器
运用正则表达式不使用内置方法实现计算器
#__author__:"Jay guo"#__date__:2016/9/12import redef check(s): if re.findall("[a-zA-Z]",s) or re.findall("[*/][^\d(]",s): return else: return sdef format(s): s = s.replace(" ","") s = s.replace("++","+") s = s.replace("+-","-") s = s.replace("-+","-") s = s.replace("--","+") return sdef add_sub(s): ret = re.search("\d+\.?\d*[+-]\d+\.?\d*", s) if ret: x, y = re.split("[+-]", ret.group()) x = float(x) y = float(y) if "+" in ret.group(): end = x + y else: end = x - y s = s.replace(ret.group(), str(end)) s = s.replace("(","") s = s.replace(")","") return sdef mul_exc(s): ret = re.search("\d+\.?\d*[*/]\d+\.?\d*", s) if ret: x,y = re.split("[*/]",ret.group()) x = float(x) y = float(y) if "*" in ret.group(): end = x*y else: end = x/y s = s.replace(ret.group(),str(end)) s = s.replace("(","") s = s.replace(")","") return sdef main(): while True: ret = input("PLZ input>>>>: ") ret = check(ret) ret = format(ret) while True: ret = mul_exc(ret) ret = add_sub(ret) ret = format(ret) a = len(re.findall("\d+", ret)) print ("a",a,ret) if a == 2: break print (re.sub("^\+","",ret))main()
运用正则表达式不使用内置方法实现计算器
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。