def find_closing_p(s: str, opening_index: int) -> int: skips = 0 for i, c in enumerate(s[opening_index + 1:]): match c: case ')': if skips != 0: skips -= 1 else: return i + opening_index + 1 case '(': skips += 1 def do_math(s: str) -> int: tokens = [] i = 0 for c in s: if c.isdigit(): try: tokens[i] += c except IndexError: tokens.append(c) elif c in {'+', '-', '*', '/'}: i += 1 tokens.append(c) last_piece = tokens.pop(0) result = 0 for piece in tokens: result = eval(f'{last_piece}{piece}') last_piece = str(result) return result def do_parentheses(s: str) -> str: if '(' in s: opening_index: int = s.find('(') closing_index: int = find_closing_p(s, opening_index) sub_snp = s[opening_index + 1:closing_index] return str(do_math(s[:opening_index] + do_parentheses(sub_snp))) else: if len(s) == 1: return s else: return str(do_math(s)) # (5*6)-(4+(1)) def main(): s: str = input() # Wish I could just use eval() but it uses pemdas # Evaluate all parentheses while '(' in s: opening_index: int = s.find('(') closing_index: int = find_closing_p(s, opening_index) sub_snp = s[opening_index + 1:closing_index] sub_s = s[opening_index:closing_index + 1] s = s.replace(sub_s, do_parentheses(sub_snp)) print(do_math(s)) if __name__ == '__main__': main()