题解 | 四则运算

import sys

def calc(a, b, sign):
    # print('calc:', a, b, sign)
    if sign == '+':
        return a + b
    elif sign == '-':
        return a - b
    elif sign == '*':
        return a * b
    elif sign == '/':
        return a / b
    else:
        return None

def eval_str(input_str:str):
    # if len(input_str) == 1 or len(input_str) == 2 and input_str.startswith('-'):
    #     return int(input_str)
    idx = 0
    nums = []
    signs = []
    replace_dict = dict(zip(['{','}','[',']'], ['(',')','(',')']))
    input_str = input_str.translate(str.maketrans(replace_dict))
    # print(input_str)
    para_num = 0
    while idx < len(input_str):
        c = input_str[idx]
        if input_str[idx] == '(':
            start = idx + 1
            para_num += 1
            while para_num > 0:
                idx += 1
                if input_str[idx] == '(':
                    para_num += 1
                elif input_str[idx] == ')':
                    para_num -= 1
            para_res = eval_str(input_str[start:idx])
            if nums and signs[-1] in {'*', '/'}:
                nums.append(calc(nums.pop(), para_res, signs.pop()))
            else:
                nums.append(para_res)   
        else:
            if c.isdigit():
                pre_idx = idx
                while(idx + 1 < len(input_str)) and input_str[idx+1].isdigit():
                    idx += 1
                c = input_str[pre_idx:idx+1]
                if len(signs) > len(nums) and signs[-1] == '-':
                    signs.pop()
                    c = -1 * int(c)
                if nums and signs[-1] in {'*', '/'}:
                    nums.append(calc(int(c), nums.pop(), signs.pop()))
                else:
                    nums.append(int(c))
            else:
                signs.append(c)
        idx += 1
    rev_nums = nums[::-1]
    rev_signs = signs[::-1]
    # print('rev_nums:', rev_nums)
    # print('rev_signs:', rev_signs)
    while len(rev_nums) > 1:
        a = rev_nums.pop()
        rev_nums[-1] = calc(a, rev_nums[-1], rev_signs.pop())
    # print(rev_nums)
    return int(rev_nums[0])

   
raw_input = []
for i,line in enumerate(sys.stdin):
    raw_input.append(line.strip())
    if i == 1:
        break

input_str = raw_input[0]
print(eval_str(input_str))
# 3+2*{1+2*[4/(8-6)+7]}
# 3+2*{1+2*[-4/(8-6)+7]}

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务