题解 | 小红的能量校准 Python3

小红的能量校准

https://www.nowcoder.com/practice/3fc28183185b49199ba9d7cc5abe82db?tpId=390&tqId=11610323&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37

import sys

def loadTree(s):
    precedence = {'(': 0, '+': 1, '*': 2}
    v_s, op_s = [], []
    i = 0
    while i < len(s):
        if s[i].isdigit():
            num = [s[i]]
            while (i + 1) < len(s) and s[i+1].isdigit():
                num.append(s[i+1])
                i += 1
            v_s.append(int(''.join(num)))
        elif s[i] == '(':
            op_s.append(s[i])
        elif s[i] in precedence:
            while op_s and precedence[op_s[-1]] > precedence[s[i]]:
                v_s.append(op_s.pop())
            op_s.append(s[i])
        elif s[i] == ')':
            while op_s[-1]!='(':
                v_s.append(op_s.pop())
            op_s.pop()
        else:# x
            v_s.append(s[i])
        i += 1
    while op_s:
        v_s.append(op_s.pop())
    return v_s
def cal(v_s, x):
    stack = []
    for i in range(len(v_s)):
        if v_s[i] not in ['*', '+']:
            if v_s[i] == 'x':
                stack.append(x)
            else:
                stack.append(v_s[i])
        else:
            x1 = stack.pop()
            x2 = stack.pop()
            if v_s[i] == '+':
                stack.append(x1 + x2)
            else:
                stack.append(x1 * x2)
    return stack[-1]
s0 = sys.stdin.read()
s1, s2 = s0.split('=')
s = [s1[0]]
for i in range(1, len(s1)):
    if (s1[i] in ['x', '('] and s1[i-1].isdigit()) or (s1[i-1] in ['x', ')'] and s1[i].isdigit() or (s1[i]=='(' and s1[i-1]==')')):
        s.append('*')
    s.append(s1[i])
v_s = loadTree(s)
k_b = cal(v_s, 1)
b = cal(v_s, 0)

print(int((int(s2) - b) / (k_b -b)))

+ 补充缺少的`*`运算符,需要考虑`)(``数字(``)数字``数字x``x数字`情况

+ 中缀表达式转后缀表达式`loadTree`

+ `cal`后缀表达式计算 `k+b`和`k`

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 17:04
点赞 评论 收藏
分享
01-27 15:41
门头沟学院 Java
想躺平的菜鸡1枚:我项目比你难、学历比你好、还有SCI论文,投java都被拒一大片,现在基本上都要问点agent开发
软件开发投递记录
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务