Problem:


ICPC Calculator

In mathematics, we usually specify the order of operations by using
parentheses.
For example, 7 × (3 + 2) always means multiplying 7 by the result of 3 + 2 and never means adding 2 to the result of 7 × 3.

However, there are people who do not like parentheses.
International Counter of Parentheses Council (ICPC) is attempting
to make a notation without parentheses the world standard.
They are always making studies of such no-parentheses notations.

Dr. Tsukuba, a member of ICPC, invented a new parenthesis-free notation.
In his notation, a single expression is represented by multiple
lines, each of which contains an addition operator (+), a
multiplication operator (*) or an integer.
An expression is either a single integer or an operator application to operands.
Integers are denoted in decimal notation in one line.
An operator application is denoted by a line of its operator immediately
followed by lines denoting its two or more operands,
each of which is an expression, recursively.
Note that when an operand is an operator application,
it comprises multiple lines.

As expressions may be arbitrarily nested,
we have to make it clear which operator is applied to which operands.
For that purpose, each of the expressions is given its nesting level.
The top level expression has the nesting level of 0.
When an expression of level n is an operator application,
its operands are expressions of level n + 1.
The first line of an expression starts with a sequence of periods (.),
the number of which indicates the level of the expression.

For example, 2 + 3 in the regular mathematics is denoted as in Figure 1.
An operator can be applied to two or more operands.
Operators + and * represent operations
of summation of all operands and multiplication of all operands,
respectively.  For example, Figure 2 shows an expression multiplying
2, 3, and 4.
For a more complicated example, an expression (2 + 3 + 4) × 5 in
the regular mathematics can be expressed as in Figure 3 while (2 + 3) × 4 × 5
can be expressed as in Figure 4.

+
.2
.3

Figure 1: 2 + 3

*
.2
.3
.4

Figure 2: An expression multiplying 2, 3, and 4

*
.+
..2
..3
..4
.5

Figure 3: (2 + 3 + 4) × 5

*
.+
..2
..3
.4
.5

Figure 4: (2 + 3) × 4 × 5

  Your job is to write a program that computes the value of expressions
  written in Dr. Tsukuba's notation to help him.

Input

  The input consists of multiple datasets.  Each dataset
  starts with a line containing a positive integer n, followed by
  n lines denoting a single expression in Dr. Tsukuba's notation.

  You may assume that, in the expressions given in the input,
  every integer comprises a single digit and that
  every expression has no more than nine integers.
  You may also assume that all the input expressions are valid
  in the Dr. Tsukuba's notation.
  The input contains no extra characters, such as spaces or empty lines.

  The last dataset is immediately followed by a line with a single zero.

Output

For each dataset, output a single line containing an integer
which is the value of the given expression.

Sample Input

1
9
4
+
.1
.2
.3
9
+
.0
.+
..*
...1
...*
....1
....2
..0
10
+
.+
..6
..2
.+
..1
..*
...7
...6
.3
0

Output for the Sample Input

9
6
2
54



Sample input:
1
9
4
+
.1
.2
.3
9
+
.0
.+
..*
...1
...*
....1
....2
..0
10
+
.+
..6
..2
.+
..1
..*
...7
...6
.3
0


Sample output:
9
6
2
54

Submission status: Wrong Answer

Solution code:
def calc(p, nums):
    if p == '+':
        ans = sum(nums)
    else:
        ans = 1
        for i in nums:
            ans *= i
    return ans

while True:
    n = int(input())
    if n == 0:
        quit()
    w = []
    depth = 0
    for i in range(n):
        t = input()
        td = t.count('.')
        tc = t.replace('.', '')
        if tc.isdigit():
            tc = int(tc)
        else:
            td += 1
        w.append([td, tc])
        depth = max(depth, td)

    # while len(w) != 1:
    while depth > 0:
        # print(w)
        for i in range(len(w)):
            if w[i][0] == depth:
                temp = []
                for j in range(i+1, len(w)):
                    # print(w[j][1], j)
                    if w[j][0] == depth and str(w[j][1]).isdigit():
                        temp.append(w[j][1])
                # print(w[i][1], temp)
                ta = calc(w[i][1], temp)
                # print(ta)
                if j >= len(w):
                    w = w[:i] + [[depth - 1, ta]]
                else:
                    w = w[:i] + [[depth - 1, ta]] + w[j:]
                # w = w[:i] + w[depth, ta] + w[j:]
                break
        depth -= 1
    print(w[0][1])

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python

from collections import deque
import itertools as it
import sys
import math

while True:
    n = input()
    lst = []
    if n == 0:
        break
    if n == 1:
        num = input()
        print num
        continue
    for loop in range(n):
        S = raw_input()
        lst.append((len(S), S[-1]))
    
    c_lst = [0 for i in range(1000)]
    v_lst = [0 for i in range(1000)]

    rank = 1
    for i in range(n):
        r = lst[i][0]
        c = lst[i][1]
        while r < rank:
            if c_lst[rank - 1] == '+':
                v_lst[rank - 1] += v_lst[rank]
            else:
                v_lst[rank - 1] *= v_lst[rank]
            rank -= 1
        if c == '+':
            r += 1
            c_lst[r] = '+'
            v_lst[r] = 0
            rank += 1
            continue
        elif c == '*':
            r += 1
            c_lst[r] = '*'
            v_lst[r] = 1
            rank += 1
            continue
        if c_lst[r] == '+':
            v_lst[r] += int(c)
        else:
            v_lst[r] *= int(c)
    print v_lst[2]

Submission status: Accepted

Solution code:
# AOJ 1602: ICPC Calculator
# Python3 2018.7.13 bal4u

def calc(lvl, idx):
	c = e[idx][lvl]
	if c.isdigit(): return [int(c), idx+1]
	lvl, idx = lvl+1, idx+1
	x = 0 if c == '+' else 1
	while idx < len(e):
		f = i = 0
		while i < len(e[idx]) and i < lvl:
			if e[idx][i] != '.': break
			i += 1
		if i < lvl: break
		if e[idx][i].isdigit(): y, f = int(e[idx][i]), 1
		else: y, idx = calc(lvl, idx)
		x = x+y if c == '+' else x*y
		if f: idx += 1
	return [x, idx]

while True:
	n = int(input())
	if n == 0: break
	e = [list(input()) for i in range(n)]
	print(calc(0, 0)[0])

Submission status: Accepted

Solution code:
ans_list = []
def calclater(a, num_list):
    if a == "*":
        ans = 1
        for i in num_list:
            ans *= int(i)
    elif a == "+":
        ans = 0
        for i in num_list:
            ans += int(i)
    return str(ans)

while True:
    n = int(input())
    if not n:
        break
    s_list = [[] for i in range(100)]
    now = 0
    now_len = 0
    for i in range(n):
        s = input()
        if not i:
            s_list[0] = [s]
            now_len = len(s)
        else:
            if len(s) == now_len:
                s_list[now].append(s[-1])
            elif len(s) > now_len:
                now += 1
                s_list[now] = [s[-1]]
                now_len = len(s)
            elif len(s) < now_len:
                while len(s) < now_len:
                    s_list[now - 1][-1] = str(calclater(s_list[now - 1][-1], list(s_list[now])))
                    s_list[now] = []
                    now_len -= 1
                    now -= 1
                s_list[now].append(s[-1])

    for i in range(now - 1, -1, -1):
        s_list[i][-1] = str(calclater(s_list[i][-1], s_list[i + 1]))

    ans_list.append(s_list[0][0])

for i in ans_list:
    print(i)

Submission status: Accepted

Solution code:
def product(lst):
    ret = 1
    for i in lst:
        ret *= i
    return ret

def dfs(lst, index, level):
    nums = []
    for i in range(index, len(lst)):
        dn = lst[i].count(".")
        if level == dn:
            s = lst[i][level]
            if s=='+':
                nums.append(sum(dfs(lst, i+1, level+1)))
            elif s=='*':
                nums.append(product(dfs(lst, i+1, level+1)))
            else:
                nums.append(int(s))
        elif level > dn:
            break
    return nums

while True:
    n = int(input())
    if not n:
        break
    ls = [input() for i in range(n)]
    print(dfs(ls, 0, 0)[0])

Submission status: Accepted

Solution code:
def expression(ss, i, c_level):
    s = ss[i]
    code = s[-1]
    if code == "+":
        return plus(ss, i+1, c_level+1)
    elif code == "*":
        return product(ss, i+1, c_level+1)
    return int(s[c_level:])

def plus(ss, i, c_level):
    num = 0
    while i < len(ss):
        s = ss[i]
        level = len(s)-1
        if level < c_level:
            break
        if c_level < level:
            i += 1
            continue
        num += expression(ss, i, c_level)
        i += 1
    return num

def product(ss, i, c_level):
    num = 1
    while i < len(ss):
        s = ss[i]
        level = len(s)-1
        if level < c_level:
            break
        if c_level < level:
            i += 1
            continue
        num *= expression(ss, i, c_level)
        i += 1
    return num

while 1:
    n = input()
    if n == 0:
        break
    ss = [raw_input() for i in xrange(n)]
    print expression(ss, 0, 0)

Submission status: Accepted

Solution code:
def parser(i):
    idx = i
    dep = s[i].count('.')
    i += 1
    arr = []
    while i < N and s[i].count(".") > dep:
        if "+" in s[i] or "*" in s[i]:
            num, i = parser(i)
            arr.append(num)
        else:
            arr.append(int(s[i].replace('.', '')))
        i += 1
    if "+" in s[idx]:
        return sum(arr), i - 1
    else:
        ret = 1
        for num in arr:
            ret *= num
        return ret, i - 1

while True:
    N = int(input())
    if not N:
        break
    if N == 1:
        print(input())
        continue
    s = [input() for _ in range(N)]
    print(parser(0)[0])

Submission status: Accepted

Solution code:
while True:
    n=int(input())
    if n==0:
        break;
    elif n==1:
        print(input())
        continue;
    li=[input() for i in range(n)]
    index=0
    def pls(depth):
        k=0
        global index
        while len(li[index])>depth and li[index][depth-1]=='.':
            if (not li[index][depth]=='+') and (not li[index][depth]=='*'):
                k+=int(li[index][depth])
                index+=1
            elif li[index][depth]=='+':
                index+=1
                k+=pls(depth+1)
            elif li[index][depth]=='*':
                index+=1
                k+=prd(depth+1)
            if index==n:
                return k    
        else:
            return k
    def prd(depth):
        k=1
        global index
        while len(li[index])>depth and li[index][depth-1]=='.':
            if (not li[index][depth]=='+') and (not li[index][depth]=='*'):
                k*=int(li[index][depth])
                index+=1
            elif li[index][depth]=='+':
                index+=1
                k*=pls(depth+1)
            elif li[index][depth]=='*':
                index+=1
                k*=prd(depth+1)
            if index==n:
                return k
        else:
            return k
    if li[0]=='+':
        index+=1
        print(pls(1))
    elif li[0]=='*':
        index+=1
        print(prd(1))

Submission status: Accepted

Solution code:
def resolve():
    n = int(input())
    if n == 0:
        return False

    field = []
    def add(a):
        result = 0
        for i in a:
            result += i
        return result

    def mult(a):
        result = 1
        for i in a:
            result *= i
        return result


    op = {"+": add, "*": mult}


    for i in range(n):
        s = input()
        a = [s.count("."), s.replace(".", "")]
        if a[1] not in op:
            a[1] = int(a[1])
        field.append(a)

    values = []
    while field:
        target = field.pop()
        if target[1] not in op:
            values.append(target)
        else:
            operands = []
            for v in values[::-1]:
                if v[0] != target[0] + 1:
                    break
                operands.append(v[1])
                values.remove(v)
            target[1] = op[target[1]](operands)
            values.append(target)
    print(values[0][1])
    return True


while resolve(): pass

Submission status: Accepted

Solution code:
opr_list = ["+", "*"]


def solve():
    N = int(input())
    while(N != 0):
        if(N == 1):
            print(int(input()))
        else:
            ans = [0 for i in range(20)]
            s = []
            opr = [0 for i in range(20)]
            for i in range(N):
                s.append(list(input()))
            layer = 0
            for i in range(N):
                nowlayer = s[i].count(".")
                if(nowlayer < layer):
                    while(nowlayer < layer):
                        if(opr[layer-2] == "+"):
                            ans[layer-1] += ans[layer]
                        else:
                            ans[layer-1] *= ans[layer]
                        layer -= 1
                if(s[i][-1] in opr_list):
                    opr[nowlayer] = s[i][-1]
                    ans[nowlayer + 1] = 0 if opr[nowlayer] == "+" else 1
                    layer += 1
                else:
                    if(opr[nowlayer-1] == "+"):
                        ans[nowlayer] += int(s[i][-1])
                    else:
                        ans[nowlayer] *= int(s[i][-1])
                layer = nowlayer
            if(layer > 1):
                while(layer > 1):
                    if(opr[layer-2] == "+"):
                        ans[layer-1] += ans[layer]
                    else:
                        ans[layer-1] *= ans[layer]
                    layer -= 1
            print(ans[1])
        N = int(input())


solve()

Submission status: Accepted

Solution code:
while 1:
    n = input()
    if n == 0:
        break
    st = [[]]
    for i in xrange(n):
        s = raw_input()
        lev = s.count('.')
        v = s[lev:]
        while lev+1 < len(st):
            top = st.pop()
            op = st[-1].pop()
            if op == '+':
                st[-1].append(sum(top))
            else:
                st[-1].append(reduce(lambda x,y: x*y, top))
        if v in '+*':
            st[lev].append(v)
            st.append([])
        else:
            st[lev].append(int(v))
    while len(st) > 1:
        top = st.pop()
        op = st[-1].pop()
        if op == '+':
            st[-1].append(sum(top))
        else:
            st[-1].append(reduce(lambda x,y: x*y, top))
    print st[-1][0]

Submission status: Accepted

Solution code:
def inp():
	global n
	n = int(input())
	return n
def strinp():
	l = 0
	s = list(input())
	for i in s:
		if i == '.':
			l += 1
		else:
			c = i
	return [l,c]
def calc(p):
	global f
	l = f[p][0]
	c = f[p][1]
	p += 1
	if c == '+':
		ans = 0
		for i in range(p,n):
			if f[i][0] == l:
				break
			elif f[i][0] == l+1:
				ans += calc(i)
	elif c == '*':
		ans = 1
		for i in range(p,n):
			if f[i][0] == l:
				break
			elif f[i][0] == l+1:
				ans *= calc(i)
	else:
		ans = int(c)
	return ans

while inp() > 0:
	f = []
	for i in range(n):
		f.append(strinp())
	print(calc(0))

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    rr = []
    ii = [2**i for i in range(6)]

    while True:
        n = I()
        if n == 0:
            break
        a = [S() for _ in range(n)]
        d = 0
        s = [[]]
        for c in a:
            l = len(c)
            while l <= d:
                if s[-1][0] == '+':
                    k = 0
                    for kc in s[-1][1:]:
                        k += kc
                else:
                    k = 1
                    for kc in s[-1][1:]:
                        k *= kc
                s = s[:-1]
                s[-1].append(k)
                d -= 1

            t = c[-1]
            if t == '+' or t == '*':
                d += 1
                s.append([t])
            else:
                s[-1].append(int(t))

        while len(s) > 1:
            if s[-1][0] == '+':
                k = 0
                for kc in s[-1][1:]:
                    k += kc
            else:
                k = 1
                for kc in s[-1][1:]:
                    k *= kc
            s = s[:-1]
            s[-1].append(k)

        rr.append(s[0][0])


    return '\n'.join(map(str, rr))


print(main())

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from collections import defaultdict
def inpl(): return list(map(int, input().split()))

N = int(input())

def cal(i):
    if B[i] == "*":
        tmp = 1
        for g in G[i]:
            tmp *= cal(g)
    elif B[i] == "+":
        tmp = 0
        for g in G[i]:
            tmp += cal(g)
    else:
        tmp = int(B[i])
    return tmp

while N:
    A = [0]*N
    B = [0]*N
    for i in range(N):
        x = input()
        A[i], B[i] = x.count("."), x.replace(".", "")
    G = [[] for _ in range(N)]
    D = defaultdict(int)
    for i, a in enumerate(A):
        D[a] = i
        if a > 0:
            G[D[a-1]].append(i)
    print(cal(0))
    N = int(input())

Submission status: Accepted

Solution code:
import re
def dotexit(s):
  return re.sub("^\.","",s)

def prod(l):
  x=1
  for i in l:
    x *= i
  return x

def rec(s):
  nums=[dotexit(x) for x in s[1:]]
  ad = []
  for i in range(len(nums)):
    if nums[i]=='+' or nums[i]=='*':
      rl=[nums[i]]
      for j in range(i+1,len(nums)):
        if nums[j][0] == '.':
          rl.append(nums[j])
        else:
          break
      ad.extend(rec(rl))
  nums.extend(ad)
  nums = [x for x in nums if x !='+' and x != '*' and x[0]!='.']
  if s[0]=='+':
    return [str(sum([int(x) for x in nums]))]
  elif s[0]=='*':
    return [str(prod([int(x) for x in nums]))]
  else:
    return s

while True:
  n=int(input())
  if n==0:
    break
  s=[]
  for i in range(n):
    s.append(input())
  print(rec(s)[0])

Submission status: Accepted

Solution code:
def cal(lst,op):
	if op == '+':
		return sum(lst)
	else:
		ret = 1
		for num in lst:
			ret *= num
		return ret


def rec ():
	global n,S,idx
	op = S[idx][-1]
	nst = len(S[idx])
	idx += 1
	lst = []
	while idx < n:
		if len(S[idx]) <= nst:
			break
		if not S[idx][-1].isdigit():
			lst.append(rec())
		else:
			lst.append(int(S[idx][-1]))
			idx += 1
	return cal(lst,op)

while True:
	n = int(input())
	if n == 0:
		break
	if n == 1:
		print(input())
		continue
	S = []
	idx = 0
	for i in range(n):
		S.append(input())
	print(rec())

Submission status: Accepted

Solution code:
while True:
    n = int(input())
    if n == 0:break
    a = [input() for _ in range(n)]
    while True:
        if len(a) == 1:break
        c = 0
        s = 0
        for i in range(len(a)):
            if a[i].count('.') > c:
                c = a[i].count('.')
                s = i
        e = s
        while e < len(a) and a[e].count('.') == a[s].count('.'):
            e += 1
        k = a[s - 1].replace('.', '')
        b = [a[i] for i in range(s, e)]
        for i in range(len(b)):
            b[i] = int(b[i].replace('.', ''))
        if k == '+':
            a[s - 1] = '.'*a[s - 1].count('.')+str(sum(b))
            del a[s:e]
        else:
            m = 1
            for i in b:
                m *= i
            a[s - 1] = '.'*a[s - 1].count('.')+str(m)
            del a[s:e]
    print(a[0])

Submission status: Accepted

Solution code:
#!/usr/bin/env python

from collections import deque
import itertools as it
import sys
import math

while True:
    n = input()
    lst = []
    if n == 0:
        break
    if n == 1:
        num = input()
        print num
        continue
    for loop in range(n):
        S = raw_input()
        lst.append((len(S), S[-1]))
    if lst[0][1] == '+':
        lst.append((0, '0'))
    else:
        lst.append((0, '1'))
    n += 1
    
    c_lst = [0 for i in range(1000)]
    v_lst = [0 for i in range(1000)]

    rank = 1
    for i in range(n):
        r = lst[i][0]
        c = lst[i][1]
        while r < rank:
            if c_lst[rank - 1] == '+':
                v_lst[rank - 1] += v_lst[rank]
            else:
                v_lst[rank - 1] *= v_lst[rank]
            rank -= 1
        if c == '+':
            r += 1
            c_lst[r] = '+'
            v_lst[r] = 0
            rank += 1
            continue
        elif c == '*':
            r += 1
            c_lst[r] = '*'
            v_lst[r] = 1
            rank += 1
            continue
        if c_lst[r] == '+':
            v_lst[r] += int(c)
        else:
            v_lst[r] *= int(c)
    print v_lst[2]

Submission status: Accepted

Solution code:
def dfs(l):
    x = len(l[0])
    if l[0][-1] == "+":
        b = 0
        i = 1
        while i < len(l):
            if len(l[i]) == x + 1 and "0" <= l[i][-1] <= "9":
                b += int(l[i][-1])
                i += 1
            elif len(l[i]) == x + 1 and (l[i][-1] == "+" or l[i][-1] == "*"):
                f = i
                i += 1
                while i < len(l):
                    if len(l[i]) == x + 1:
                        break
                    i += 1
                b += dfs(l[f:i])

    elif l[0][-1] == "*":
        b = 1
        i = 1
        while i < len(l):
            if len(l[i]) == x + 1 and "0" <= l[i][-1] <= "9":
                b *= int(l[i][-1])
                i += 1
            elif len(l[i]) == x + 1 and (l[i][-1] == "+" or l[i][-1] == "*"):
                f = i
                i += 1
                while i < len(l):
                    if len(l[i]) == x + 1:
                        break
                    i += 1
                b *= dfs(l[f:i])
    else:
        b = int(l[0][-1])

    return b

def main(n):
    l = [input() for i in range(n)]
    print(dfs(l))

while 1:
    n = int(input())
    if n == 0:
        break
    main(n)

Submission status: Accepted

Solution code:
 

while True:
  n = int(input())
  if n == 0:
    break
  w = [input() for _ in range(n)]
  w = reversed(w)

  eles = [[] for _ in range(9)]

  for item in w:
    d,c = len(item) - 1,item[-1]

    if c == "+":
        eles[d].append(sum(eles[d+1]))
        eles[d+1] = []
    elif c == "*":
        tmp = 1
        for i in eles[d+1]:
            tmp *= i
        eles[d].append(tmp)
        eles[d+1] = []
    else:
        eles[d].append(int(c))


    

  print(eles[0][0])

Submission status: Accepted

Solution code:
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(input())
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())


while True:
    N = inp()
    if N == 0:
        break
    else:
        stack_numbers = [[] for _ in range(20)]
        stack_symbols = ['' for _ in range(20)]
        bL = -1
        for _ in range(N):
            S = input()
            L = len(S)
            #print(stack_symbols)
            #print(stack_numbers)
            if L < bL:
                for i in reversed(range(L,bL)):
                    if stack_symbols[i] == '+':
                        for j in range(1,len(stack_numbers[i])):
                            stack_numbers[i][j] += stack_numbers[i][j-1]
                    else:
                        for j in range(1,len(stack_numbers[i])):
                            stack_numbers[i][j] *= stack_numbers[i][j-1]
                    stack_numbers[i-1].append(stack_numbers[i][-1])
                    stack_numbers[i] = []
                    stack_symbols[i] = ''
                    #print(stack_numbers)

            s = S[-1]
            if 48 <= ord(s) <= 57:
                s = int(s)
                stack_numbers[L-1].append(s)
            else:
                stack_symbols[L] = s
            bL = L

        L = 0
        for i in reversed(range(L,bL)):
            if stack_symbols[i] == '+':
                for j in range(1,len(stack_numbers[i])):
                    stack_numbers[i][j] += stack_numbers[i][j-1]
            else:
                for j in range(1,len(stack_numbers[i])):
                    stack_numbers[i][j] *= stack_numbers[i][j-1]
            stack_numbers[i-1].append(stack_numbers[i][-1])
            stack_numbers[i] = []
            stack_symbols[i] = ''

        print(stack_numbers[-1][0])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def calc(i, level, fs, lim):
    if fs[i][1] not in "+*":
        return i, int(fs[i][1])
    if fs[i][1] == "+":
        tmp = 0
        j = i+1
        while j < lim:
            if fs[j][0] <= level:
                break
            if fs[j][1] in "*+":
                j, tmp2 = calc(j, level+1, fs, lim)
                tmp += tmp2
            else:
                tmp += int(fs[j][1])
            j += 1
        return j-1, tmp
    elif fs[i][1] == "*":
        tmp = 1
        j = i+1
        while j < lim:
            if fs[j][0] <= level:
                break
            if fs[j][1] in "*+":
                j, tmp2 = calc(j, level+1, fs, lim)
                tmp *= tmp2
            else:
                tmp *= int(fs[j][1])
            j += 1
        return j-1, tmp


def main():
    while True:
        n = int(input())
        if n == 0:
            break
        fs = [[0,0] for i in range(n)]

        for i in range(n):
            tmp = input().strip()
            fs[i][0] = tmp.count(".")
            fs[i][1] = tmp.replace(".", "")
        _, ans = calc(0, 0, fs, len(fs))
        print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
ans_list = []

def calc(i0=0):
    if S[i0][-1] == "+":
        res = 0
        for i in range(i0+1,n):
            if len(S[i]) == len(S[i0]) + 1:
                res += calc(i)
            elif len(S[i]) <= len(S[i0]):
                return res
    elif S[i0][-1] == "*":
        res = 1
        for i in range(i0+1,n):
            if len(S[i]) == len(S[i0]) + 1:
                res *= calc(i)
            elif len(S[i]) <= len(S[i0]):
                return res
    else:
        res = int(S[i0][-1])
    return res

while True:
    n = int(input())
    if n == 0:
        break
    S = [input() for _ in range(n)]

    ans = calc()
    ans_list.append(ans)

for ans in ans_list:
    print(ans)

Submission status: Accepted

Solution code:
def solve(x,a,ind):
#    print(x,a,ind)
    if "0" <= a[0][ind] <="9":
        return int(a[0][ind])

    if a[0][ind] =="+":
        i = j= 1
        su = 0
        while(i < x):
            if a[i][ind+1] == "+" or a[i][ind+1]=="*":
                j+=1
                while j < x and a[j][ind +1]==".":
                    j += 1
                su += solve(j-i,a[i:j],ind+1)
                i = j
                j = j
            else:
                su += int(a[j][ind+1])
                i += 1
                j += 1

#        print(x,a,ind,su)
        return su


    if a[0][ind] =="*":
        i = j= 1
        su = 1
        while(i < x):
            if a[i][ind+1] == "+" or a[i][ind+1]=="*":
                j+=1
                while j<x and a[j][ind +1]==".":
                    j += 1
                su *= solve(j-i,a[i:j],ind+1)
                i = j
                j = j
            else:
                su *= int(a[j][ind+1])
                i += 1
                j += 1
 #       print(x,a,ind,su)
        return su


while(1):
    n  = int(input())
    if n >0:
        a = [input() for i in range(n)]
        print(solve(n,a,0))
    else:
        break

Submission status: Accepted

Solution code:
import re

while True :
    n = int(input())
    if n == 0:break
    s = [input() for _ in range(n)]
    stack = []

    for n in reversed(s):
        if re.match("\.*(\+|\*)",n):
            ope = n[-1]
            depth = n.count(".") + 1
            if ope == "+":ans = 0
            else: ans = 1
            for i,a in enumerate(reversed(stack)):
                if re.match("\."*depth+"\d",a):
                    num = int(re.sub("\.*", "", stack.pop()))
                    if ope == "+":
                        ans += num
                    else:
                        ans *= num
            stack.append("."*(depth-1)+str(ans))
        else:
            stack.append(n)
    print(stack[0])

Submission status: Accepted

Solution code:
from sys import setrecursionlimit
setrecursionlimit(10 ** 8)

def mul(A):
    res = 1
    for a in A:
        res *= a
    return res

O = {'+': sum, '*': mul}


class Source():
    def __init__(self, S, i = 0):
        self.S = S
        self.pos = i

def peek(S):
    return S.S[S.pos] if S.pos < len(S.S) else 'a'

def next(S):
    S.pos += 1

def level_off(S):
    lv = 0
    while peek(S) == '.':
        lv += 1
        next(S)

    return lv

def level(S):
    i = S.pos
    lv = 0
    while peek(S) == '.':
        lv += 1
        next(S)

    S.pos = i
    return lv

def expr(S, lv, ope):
    A = []
    while peek(S) != 'a' and level(S) == lv:
        level_off(S)
        A.append(factor(S, lv))
    return ope(A)

def factor(S, lv):
    if peek(S) in O:
        ope = O[peek(S)]
        next(S)
        return expr(S, lv + 1, ope)
    return num(S)

def num(S):
    res = int(peek(S))
    next(S)

    return res


while True:
    n = int(input())
    if n == 0:
        break
    S = []
    for i in range(n):
        S.append(input())
    print(expr(Source(''.join(S)), 0, O['+']))