计算器制作

2019-05-08 07:31:41来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

import re
def chen_chu(str):
    res = re.search("[^()]+",str)
    res_l = re.split("[*/]",res.group())
    res_f_l = re.findall("[*/]",res.group())
    n = None
    for i in range(len(res_l)):
        if n:
            if res_f_l[i-1] == "*":
                n *= int(res_l[i])
            elif res_f_l[i-1] == "/":
                n /= int(res_l[i])
        else:
            n = int(res_l[i])
    return int(n)


def add_sub(str):
    res = re.search("[^()]+",str)
    res_l = re.split("[-+]",res.group())
    res_f_l = re.findall("[-+]",res.group())
    if re.match("[-+]",res.group()):
        if res_f_l[0] == "-":
            res_l[1] = -int(res_l[1])
        res_l = res_l[1:]
        res_f_l = res_f_l[1:]
        if len(res_f_l) == 0:
            return res_l[0]
    n = None
    for i in range(len(res_l)):
        if n:
            if res_f_l[i-1] == "+":
                n += int(res_l[i])
            elif res_f_l[i-1] == "-":
                n -= int(res_l[i])
        else:
            n = int(res_l[i])
    return int(n)


def ts(ret):
    new_ret = []
    for index,item in enumerate(ret):
        if item.endswith("*") or item.endswith("/"):
            new_ret.append("%s-%s" %(ret[index],ret[index+1]))
        elif re.search("[*/]",ret[index]):
            new_ret.append(ret[index])
    return new_ret


if __name__ == "__main__":
    # a = "2+(3*(2+2-6)+5*3)"
    a = input("清输入计算公式:")
    a = a.replace(" ","")
    count = 2
    while True and count > 0:
        ret = re.search(r"\([^()]+\)",a)
        if ret:
            ret_v = ret.group()
        else:
            count -= 1
            ret_v = a
        if "+" in ret_v or "-" in ret_v:
            if "*" in ret_v or "/" in ret_v:
                res = re.findall("[^()]+",ret_v)
                res_l = re.split(r"[-+]",res[0])
                res_l = ts(res_l)
                for item in res_l:
                    res_l_v = chen_chu(item)
                    a = a.replace(item,str(res_l_v))
                    a =a.replace("+-","-")
                    a = a.replace("--","+")
            else:
                res_l_v = add_sub(ret_v)
                a = a.replace(ret_v, str(res_l_v))
                a = a.replace("+-", "-")
                a = a.replace("--", "+")
        else:
            if "*" in ret_v or "/" in ret_v:
                res_l_v = chen_chu(ret_v)
                a = a.replace(ret_v, str(res_l_v))
                a = a.replace("+-", "-")
                a = a.replace("--", "+")
        print(a)


 


原文链接:https://www.cnblogs.com/saber9/p/10822826.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:day02

下一篇:python爬虫框架—Scrapy安装及创建项目