计算器制作

Posted saber9

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计算器制作相关的知识,希望对你有一定的参考价值。

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)


 

以上是关于计算器制作的主要内容,如果未能解决你的问题,请参考以下文章

想要使用 SharePreferences 更新第二个片段中的数据,但第二个片段没有更新

ppt中的三维效果怎么使用

使用从循环内的代码片段中提取的函数避免代码冗余/计算开销

为片段制作自定义列表视图?

如何在片段内制作 Swip ActionBar-Tabs

在片段中制作用于开始活动的图像按钮?