python(计算机)

# Author:Sooele
import re

def main():
    while True:
        a = input("请输入你想计算的数学方程式,先小括号(请输入半角的括号,不要输入中文的),后加减乘除\n")
        a = a.replace(' ', '')
        #replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
        #print(a)
        if re.search(r"[0-9\+\-\*/()\.]+", a) == None:    #如果匹配的搜索不是列表中的符号就输出下面的结果,结束
            print("匹配失败,输入格式错误,请重新输入\n")
            continue
        elif a.count('(') != a.count(')'):  #如果'('的个数不等于')'
            print('你写的括号左右个数不匹配')
            continue
        elif len(re.search(r"[0-9\+\-\*/()\.]+", a).group().search()) != len(a):#re.searchd的字符串长度不等于a
            print("输入格式错误,请重新输入\n")
            continue
        else:
            while True:
                if '(' in a: #
                    ct = re.search(r'\([^()]+\)', a)#计算出第一个()里的算式
                    if ct is not None:     #如果ct是没有的话
                        b = ct.group() #输出 print("输入格式错误,请重新输入\n")
                        c = chengfa_chufa(b)  #
                        a = re.sub(r'\(([^()]+)\)', str(c), a, 1) #搜索
                    else:
                        c = chengfa_chufa(a)
                        print(c)
                        break
                break
def jiajianfa(a):
    '''
    计算加减法
    :param:
    :return:
    '''

    if '--' in a:
        a = a.replace('--', '+')

    c = re.findall(r'-?\d+\.?\d*', a) #-123456.132123
    ls = []
    for i in c:
        ls.append(float(i))
    rest = sum(ls)
    return rest


def chengfa(a):
    '''
    计算乘法
    :param ct:
    :return:
    '''

    b = re.search(r'\d+\.?\d*(\*-?\d+\.?\d*)+', a)  #132132.654645*-564564.456456*-5645645.654561651615
    if b is not None:
        b = b.group()
        rest = 1
        c = re.findall(r'-?\d+\.?\d*', b)
        ls = []
        for item in c:
            ls.append(float(item))
        for i1 in range(len(ls)):
            rest = rest * ls[i1]
        a = re.sub(r'\d+\.?\d*(\*-?\d+\.?\d*)+', str(rest), a, 1)
        return a

def chufa(a):
    '''
    计算出发
    :param a:
    :return:
    '''

    b = re.search(r'\d+\.?\d*(\/-?\d+\.?\d*)+', a) #523.5564561/-1231.564564/-1344.4546
    if b is not None:
        b = b.group()
        c = re.findall(r'-?\d+\.?\d*', b)
        ls = []
        for i in c:
            ls.append(float(i))
        rest = ls[0]
        for i1 in range(1, len(ls)):
            rest = rest / ls[i1]
        a = re.sub(r'\d+\.?\d*(\/-?\d+\.?\d*)+', str(rest), a, 1)
        return a

def chengfa_chufa(b):
    '''
    计算结果
    :return:
    '''
    while True:
        if '*' in b:
            c = b.split('*')
            if '/' in c[0]:
                b = chufa(b)
            else:
                b = chengfa(b)
        elif '/' in b:
            b = chufa(b)

        elif '+' or '-' in b:
            b = jiajianfa(b)
            return b
        else:
            return b


main()

发表评论