def parse(s) root = [] stack = [root] s.scan(/\d+|\D/) do |t| if t == '(' stack << [] elsif t == ')' st = stack.pop stack.last << st elsif t == '+' || t == '-' stack.last << t else stack.last << t.to_i end end root end def evaluate(ast) return ast if ast.instance_of?(Integer) ast.each_with_index.inject(0) do |s,(t,i)| next s if t.instance_of?(String) (i == 0 || ast[i - 1] == '+') ? (s + evaluate(t)) : (s - evaluate(t)) end end puts evaluate(parse(gets.chomp))