import sys class Soloution: def get_lisp_ast_result(self, eavl_str): if len(eavl_str) < 2 or eavl_str[0] != '(' or eavl_str[-1] != ')': print(-1) return # store infos with a stack stack = list() index = 0 space_count = 0 while index < len(eavl_str): # check if two or more spaces if space_count > 1: print(-1) return if eavl_str[index] == ' ': index += 1 space_count += 1 continue space_count = 0 if eavl_str[index] != ')': stack.append(eavl_str[index]) else: tmp = list() flag = False while len(stack) > 0: val = stack.pop() if val == '(': flag = True break tmp.insert(0, val) if not flag: print(-1) return rs = None # eavl strs if tmp[0] == '+': rs = self.do_add(tmp) elif tmp[0] == '*': rs = self.do_multi(tmp) elif tmp[0] == '^': rs = self.do_iadd(tmp) if rs is None: print(-1) return else: # end with legal ast str if len(stack) == 0: print(rs) return stack.append(str(rs)) index += 1 if len(stack) > 1 or not stack[0].isnumeric(): print(-1) else: print(stack[0]) def do_add(self, strs): if len(strs) != 3 or not strs[1].isnumeric() or not strs[2].isnumeric(): return return int(strs[1]) + int(strs[2]) def do_multi(self, strs): if len(strs) != 3 or not strs[1].isnumeric() or not strs[2].isnumeric(): return return int(strs[1]) * int(strs[2]) def do_iadd(self, strs): if len(strs) != 2 or not strs[1].isnumeric(): return return int(strs[1])+1 if __name__ == '__main__': args = sys.stdin.readline().strip() solution = Soloution() solution.get_lisp_ast_result(args)
点赞 6

相关推荐

06-28 22:48
已编辑
广东金融学院 Java
小浪_Coding:学院本+这俩项目不是buff叠满了嘛
点赞 评论 收藏
分享
07-23 15:05
门头沟学院 Java
熊大不大:不好意思KPI数据刚刚刷新,刚刚达标
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务