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

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

import copy
def test(demo_str):
    # 剔除空格
    demo_str = demo_str.replace(' ', '')
    # 如果只有一个数字直接输出
    if len(demo_str) == 1:
        print(demo_str)
    # 提取算术符与数字
    number = [int(demo_str[x]) for x in range(len(demo_str)) if x % 2 == 0]
    suanshu = [demo_str[x] for x in range(len(demo_str)) if x % 2 == 1]
    # 进行深拷贝,防止数据混乱
    number_new = copy.deepcopy(number)
    suanshu1 = copy.deepcopy(suanshu)
    while True:
        # 笨办法,每次先进行一次乘法或除法,在跟新数据和符号。
        for i in range(len(suanshu)):
            if suanshu[i] == "*":
                number_new[i]=number[i] * number[i + 1]
                number_new.remove(number[i + 1])
                suanshu1.remove("*")
                number = copy.deepcopy(number_new)
                suanshu = copy.deepcopy(suanshu1)
                break
            if suanshu[i] == "/":
                number_new[i]=number[i] // number[i + 1]
                number_new.remove(number[i + 1])
                suanshu1.remove("/")
                number = copy.deepcopy(number_new)
                suanshu = copy.deepcopy(suanshu1)
                break
        number = copy.deepcopy(number_new)
        suanshu = copy.deepcopy(suanshu1)
        # 如果没有乘除,跳出循环。
        if "*" not in suanshu1 and  "/" not in suanshu1:
            break
    number_new1 = copy.deepcopy(number_new)
    suanshu2 = copy.deepcopy(suanshu1)
    while True:
        # 运算加减,每次运算,赋值给第一个数,循环计算完毕。
        if suanshu1[0] == "+":
            number_new1[0] = number_new[0]+number_new[1]
            number_new1.remove(number_new[1])
            suanshu2.remove("+")
        if suanshu1[0] == "-":
            number_new1[0] = number_new[0]-number_new[1]
            number_new1.remove(number_new[1])
            suanshu2.remove("-")
        number_new = copy.deepcopy(number_new1)
        suanshu1=copy.deepcopy(suanshu2)
        if len(suanshu2) == 0:
            break
    print(number_new[0])
test('1+2*3+5/5+ 8*7-5-8')
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值