码迷,mamicode.com
首页 > 其他好文 > 详细

运用正则表达式不使用内置方法实现计算器

时间:2016-09-12 14:22:50      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

#__author__:"Jay guo"
#__date__:2016/9/12
import re
def check(s):
    if re.findall("[a-zA-Z]",s) or re.findall("[*/][^\d(]",s):
        return
    else:
        return s

def format(s):
    s = s.replace(" ","")
    s = s.replace("++","+")
    s = s.replace("+-","-")
    s = s.replace("-+","-")
    s = s.replace("--","+")
    return s


def 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 s
def 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 s

def 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()

 

运用正则表达式不使用内置方法实现计算器

标签:

原文地址:http://www.cnblogs.com/276381225q/p/5864532.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!