解决给一个字符串,里面只会出现正整数以及 +-*/ 四种符号以及空格。已知这个字符串一定是符合算式规范的,多位数版本

import re
import copy
def calculate(demo_str):

    demo_str=demo_str.replace(' ','')
    suanshu = re.findall(r'[+,\-,*,/]',demo_str)

    demo_str=re.sub(r'[+,\-,*,/]','s',demo_str)#替换算数符号
    numbers=demo_str.split('s',)#分割 是为了取出多位数
    number=[]
    for i in numbers:
        i = int(i)
        number.append(i)




#乘除运算
    while True:

        for j in range(len(suanshu)):
            if suanshu[j] == "*":
                n1=number[j] * number[j+1]
                del number[j+1]
                number[j]=n1
                number=copy.deepcopy(number)

                del suanshu[j]
                suanshu = copy.deepcopy(suanshu)
                break

            elif suanshu[j] =="/":

                n1 = number[j] //number[j + 1]
                del number[j + 1]
                number[j] = n1
                number = copy.deepcopy(number)
                del suanshu[j]
                suanshu = copy.deepcopy(suanshu)
                break
        if "*" not in suanshu and  "/" not in suanshu:
            break


#加减运算
    while True:
        for k in range(len(suanshu)):

            if suanshu[k] == "+":

                n1 = number[k] + number[k + 1]
                del number[k + 1]
                number[k] = n1
                number = copy.deepcopy(number)
                del suanshu[k]
                suanshu = copy.deepcopy(suanshu)
                break
            elif suanshu[k] =="-":
                n1 = number[k] - number[k + 1]
                del number[k + 1]
                number[k] = n1
                number = copy.deepcopy(number)
                del suanshu[k]
                suanshu = copy.deepcopy(suanshu)
                break
        if "+" not in suanshu and  "-" not in suanshu:
            break


    print(number[0])
if __name__ == '__main__':
    for test_case in [
        "1 + 1",
        "1 * 1",
        "3 /2",
        "10 + 20*3 + 4 / 2",
    ]:
        calculate(test_case)

你可能感兴趣的:(解决给一个字符串,里面只会出现正整数以及 +-*/ 四种符号以及空格。已知这个字符串一定是符合算式规范的,多位数版本)