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

计算器制作

时间:2019-05-06 23:41:01      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:[]   bsp   item   count   findall   制作   match   style   计算器   

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)


 

计算器制作

标签:[]   bsp   item   count   findall   制作   match   style   计算器   

原文地址:https://www.cnblogs.com/saber9/p/10822826.html

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