Problem:


Smart Calculator

Your task is to write a program which reads an expression and evaluates it.

The expression consists of numerical values, operators and parentheses, and the ends with '='.

The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division.

 Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right.

You may assume that there is no division by zero.

All calculation is performed as integers, and after the decimal point should be truncated

Length of the expression will not exceed 100.

-1 &times 109 ≤ intermediate results of computation ≤ 109

Input

The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression.

Output

For each datasets, prints the result of calculation.

Sample Input

2
4-2*3=
4*(8+4+3)=

Output for the Sample Input

-2
60



Sample input:
2
4-2*3=
4*(8+4+3)=


Sample output:
-2
60

Submission status: Runtime Error

Solution code:
def up_to_you(formula):
    l_p = None
    r_p = None
    for i, c in enumerate(formula):
        if c == '(':
            l_p = i
        elif c == ')':
            r_p = i
            break
    else:
        print fx(formula)
        return
        
    r = fx(formula[l_p+1:r_p])
    n_formula = formula[:l_p]+r+formula[r_p+1:]
    return up_to_you(n_formula)
            
def fx(gemstone):
    n = ''
    lis = []
    for c in gemstone:
        if c.isdigit():
            n += c
        else:
            lis.append(n)
            lis.append(c)
            n = ''
    else:
        lis.append(n)
        
    return isolation(lis)
    
def isolation(lis):
    if len(lis) == 1:
        return str(lis[0])
    o1 = None
    o = None
    o2 = None
    o_i = None
    n_lis = None
    if '*' in lis or '/' in lis:
        for i, v in enumerate(lis):
            if o1 == None:
                o1 = v
            elif v == '*' or v == '/':
                o = v
                o_i = i
            elif v == '+' or v == '-':
                o1 = None
            else:
                o2 = v
                r = discomfort(int(o1), o, int(o2))
                n_lis = lis[:(o_i-1)]+[r]+lis[(o_i+2):]
                return isolation(n_lis)
    else:
        o1 = lis[0]
        o = lis[1]
        o2 = lis[2]
        o_i = 1
        r = discomfort(int(o1), o, int(o2))
        n_lis = lis[:(o_i-1)]+[r]+lis[(o_i+2):]
        return isolation(n_lis)
                
def discomfort(o1, o, o2):
    r = None
    if o == '*':
        r = o1 * o2
    elif o == '/':
        r = o1 / o2
    elif o == '+':
        r = o1 + o2
    elif o == '-':
        r = o1 - o2
    return str(r)
    
N = int(raw_input())
for i in range(N):
    formula = raw_input().rstrip('=')
    up_to_you(formula)

Submission status: Runtime Error

Solution code:
def up_to_you(formula):
    l_p = None
    r_p = None
    for i, c in enumerate(formula):
        if c == '(':
            l_p = i
        elif c == ')':
            r_p = i
            break
    else:
        print fx(formula)
        return
        
    r = fx(formula[l_p+1:r_p])
    n_formula = formula[:l_p]+r+formula[r_p+1:]
    return up_to_you(n_formula)
            
def fx(gemstone):
    n = ''
    lis = []
    for c in gemstone:
        if c.isdigit():
            n += c
        else:
            lis.append(n)
            lis.append(c)
            n = ''
    else:
        lis.append(n)
        
    return isolation(lis)
    
def isolation(lis):
    if len(lis) == 1:
        return str(lis[0])
    o1 = None
    o = None
    o2 = None
    o_i = None
    n_lis = None
    if '*' in lis or '/' in lis:
        for i, v in enumerate(lis):
            if o1 == None:
                o1 = v
            elif v == '*' or v == '/':
                o = v
                o_i = i
            elif v == '+' or v == '-':
                o1 = None
            else:
                o2 = v
                r = discomfort(int(o1), o, int(o2))
                n_lis = lis[:(o_i-1)]+[r]+lis[(o_i+2):]
                return isolation(n_lis)
    else:
        o1 = lis[0]
        o = lis[1]
        o2 = lis[2]
        o_i = 1
        r = discomfort(int(o1), o, int(o2))
        n_lis = lis[:(o_i-1)]+[r]+lis[(o_i+2):]
        return isolation(n_lis)
                
def discomfort(o1, o, o2):
    r = None
    if o == '*':
        r = o1 * o2
    elif o == '/':
        r = o1 / o2
    elif o == '+':
        r = o1 + o2
    elif o == '-':
        r = o1 - o2
    return str(r)
    
while True:
    try:
        N = int(raw_input())
        for i in range(N):
            formula = raw_input().rstrip('=')
            up_to_you(formula)
    except EOFError:
        break

Submission status: Runtime Error

Solution code:
def up_to_you(formula):
    l_p = None
    r_p = None
    for i, c in enumerate(formula):
        if c == '(':
            l_p = i
        elif c == ')':
            r_p = i
            break
    else:
        print int(fx(formula))
        return
        
    r = fx(formula[l_p+1:r_p])
    n_formula = formula[:l_p]+r+formula[r_p+1:]
    return up_to_you(n_formula)
            
def fx(gemstone):
    n = ''
    lis = []
    for c in gemstone:
        if c.isdigit():
            n += c
        else:
            lis.append(n)
            lis.append(c)
            n = ''
    else:
        lis.append(n)
    return isolation(lis)
    
def isolation(lis):
    if len(lis) == 1:
        return str(lis[0])
    o1 = None
    o = None
    o2 = None
    o_i = None
    n_lis = None
    if '*' in lis or '/' in lis:
        for i, v in enumerate(lis):
            if o1 == None:
                o1 = v
            elif v == '*' or v == '/':
                o = v
                o_i = i
            elif v == '+' or v == '-':
                o1 = None
            else:
                o2 = v
                r = discomfort(int(o1), o, int(o2))
                n_lis = lis[:(o_i-1)]+[r]+lis[(o_i+2):]
                return isolation(n_lis)
    else:
        o1 = lis[0]
        o = lis[1]
        o2 = lis[2]
        o_i = 1
        r = discomfort(int(o1), o, int(o2))
        n_lis = lis[:(o_i-1)]+[r]+lis[(o_i+2):]
        return isolation(n_lis)
                
def discomfort(o1, o, o2):
    r = None
    if o == '*':
        r = o1 * o2
    elif o == '/':
        r = o1 / o2
    elif o == '+':
        r = o1 + o2
    elif o == '-':
        r = o1 - o2
    return str(r)
    
if __name__ == '__main__':
    N = int(raw_input())
    for i in range(N):
        formula = raw_input().rstrip('=')
        up_to_you(formula)

Submission status: Runtime Error

Solution code:
def up_to_you(formula):
    l_p = None
    r_p = None
    for i, c in enumerate(formula):
        if c == '(':
            l_p = i
        elif c == ')':
            r_p = i
            break
    else:
        print fx(formula)
        return
        
    r = fx(formula[l_p+1:r_p])
    n_formula = formula[:l_p]+r+formula[r_p+1:]
    return up_to_you(n_formula)
            
def fx(gemstone):
    n = ''
    lis = []
    for c in gemstone:
        if c.isdigit():
            n += c
        else:
            lis.append(n)
            lis.append(c)
            n = ''
    else:
        lis.append(n)
    return isolation(lis)
    
def isolation(lis):
    if len(lis) == 1:
        return str(lis[0])
    o1 = None
    o = None
    o2 = None
    o_i = None
    n_lis = None
    if '*' in lis or '/' in lis:
        for i, v in enumerate(lis):
            if o1 == None:
                o1 = v
            elif v == '*' or v == '/':
                o = v
                o_i = i
            elif v == '+' or v == '-':
                o1 = None
            else:
                o2 = v
                r = discomfort(int(o1), o, int(o2))
                n_lis = lis[:(o_i-1)]+[r]+lis[(o_i+2):]
                return isolation(n_lis)
    else:
        o1 = lis[0]
        o = lis[1]
        o2 = lis[2]
        o_i = 1
        r = discomfort(int(o1), o, int(o2))
        n_lis = lis[:(o_i-1)]+[r]+lis[(o_i+2):]
        return isolation(n_lis)
                
def discomfort(o1, o, o2):
    r = None
    if o == '*':
        r = o1 * o2
    elif o == '/':
        r = o1 / o2
    elif o == '+':
        r = o1 + o2
    elif o == '-':
        r = o1 - o2
    return str(r)
    
if __name__ == '__main__':
    N = int(raw_input())
    for i in range(N):
        formula = raw_input().rstrip('=')
        up_to_you(formula)

Submission status: Runtime Error

Solution code:
def up_to_you(formula):
    l_p = None
    r_p = None
    for i, c in enumerate(formula):
        if c == '(':
            l_p = i
        elif c == ')':
            r_p = i
            break
    else:
        print fx(formula)
        return
        
    r = fx(formula[l_p+1:r_p])
    n_formula = formula[:l_p]+r+formula[r_p+1:]
    return up_to_you(n_formula)
            
def fx(gemstone):
    n = ''
    lis = []
    add = ''
    if gemstone[0] == '-':
        gemstone = gemstone[1:]
        add = '-'
    for c in gemstone:
        if c.isdigit():
            n += c
        else:
            lis.append(add+n)
            lis.append(c)
            n = ''
            add = ''
    else:
        lis.append(add+n)
    return isolation(lis)
    
def isolation(lis):
    if len(lis) == 1:
        return str(lis[0])
    o1 = None
    o = None
    o2 = None
    o_i = None
    n_lis = None
    if '*' in lis or '/' in lis:
        for i, v in enumerate(lis):
            if o1 == None:
                o1 = v
            elif v == '*' or v == '/':
                o = v
                o_i = i
            elif v == '+' or v == '-':
                o1 = None
            else:
                o2 = v
                r = discomfort(int(o1), o, int(o2))
                n_lis = lis[:(o_i-1)]+[r]+lis[(o_i+2):]
                return isolation(n_lis)
    else:
        o1 = lis[0]
        o = lis[1]
        o2 = lis[2]
        o_i = 1
        r = discomfort(int(o1), o, int(o2))
        n_lis = lis[:(o_i-1)]+[r]+lis[(o_i+2):]
        return isolation(n_lis)
                
def discomfort(o1, o, o2):
    r = None
    if o == '*':
        r = o1 * o2
    elif o == '/':
        r = o1 / o2
        if o1 < 0: r += 1
    elif o == '+':
        r = o1 + o2
    elif o == '-':
        r = o1 - o2
    return str(r)
    
if __name__ == '__main__':
    N = int(raw_input())
    for i in range(N):
        formula = raw_input().rstrip('=')
        up_to_you(formula)

Submission status: Runtime Error

Solution code:
def seekBackOperatorInLand(op,s):
	depth = 0
	for i in xrange(len(s)-1,-1,-1):
		if s[i]==')': depth+=1
		if s[i]=='(': depth-=1
		if s[i]==op and depth==0: return i
	return None

def calc(s):
	if all(map(lambda t: t in "0123456789", s)):
		return int(s)
	if s[0]=='(' and s[-1]==')' and all(map(lambda t: t!='(' and t!=')', s[1:-1])):
		return calc(s[1:-1])
	
	p = seekBackOperatorInLand('-',s)
	if not p is None: return calc(s[:p])-calc(s[p+1:])
	p = seekBackOperatorInLand('+',s)
	if not p is None: return calc(s[:p])+calc(s[p+1:])
	p = seekBackOperatorInLand('/',s)
	if not p is None: return calc(s[:p])/calc(s[p+1:])
	p = seekBackOperatorInLand('*',s)
	if not p is None: return calc(s[:p])*calc(s[p+1:])

	return calc(s[1:-1])

def main():
	ol=input()
	for oi in xrange(ol):
		print(int(calc(raw_input()[:-1])))

main()

Submission status: Runtime Error

Solution code:
def seekBackOperatorInLand(op,s):
	depth = 0
	for i in xrange(len(s)-1,-1,-1):
		if s[i]==')': depth+=1
		if s[i]=='(': depth-=1
		if s[i]==op and depth==0: return i
	return None

def calc(s):
	if s=='':
		return 0

	if all(map(lambda t: t in "0123456789", s)):
		return int(s)
	
	p = seekBackOperatorInLand('+',s)
	if not p is None: return calc(s[:p])+calc(s[p+1:])
	p = seekBackOperatorInLand('-',s)
	if not p is None: return calc(s[:p])-calc(s[p+1:])
	p = seekBackOperatorInLand('*',s)
	if not p is None: return calc(s[:p])*calc(s[p+1:])
	p = seekBackOperatorInLand('/',s)
	if not p is None: return calc(s[:p])/calc(s[p+1:])
	
	return calc(s[1:-1])

def main():
	ol=input()
	for oi in xrange(ol):
		print test(raw_input()[:-1])

main()

Submission status: Runtime Error

Solution code:
def seekBackOperatorInLand(op,s):
	depth = 0
	for i in xrange(len(s)-1,-1,-1):
		if s[i]==')': depth+=1
		if s[i]=='(': depth-=1
		if s[i]==op and depth==0: return i
	return None

def calc(s):
	if s=='':
		return 0

	if all(map(lambda t: t in "0123456789", s)):
		return int(s)
	
	p = seekBackOperatorInLand('+',s)
	if not p is None: return calc(s[:p])+calc(s[p+1:])
	p = seekBackOperatorInLand('-',s)
	if not p is None: return calc(s[:p])-calc(s[p+1:])
	p = seekBackOperatorInLand('*',s)
	if not p is None: return calc(s[:p])*calc(s[p+1:])
	p = seekBackOperatorInLand('/',s)
	if not p is None: return calc(s[:p])/calc(s[p+1:])
	
	return calc(s[1:-1])

def main():
	ol=input()
	for oi in xrange(ol):
		s=raw_input()[:-1]
		print calc(s) #, eval(s)

main()

#?????????WA??????

Submission status: Runtime Error

Solution code:
import sys

#while 1:
#        (a,b,c) = map(int , raw_input().split())
def isdigit2(n):
    n = str(n)
    if(n.isdigit()):return True
    if(n.startwith("-")):
        if(len(n)==1):return False
        if(str(n)[1:].isdigit):return True
    return False

def parse(line):
    lis = []
    ind =0
    while(line[ind]!="="):
        a = line[ind]
        if(a.isdigit()==False):
            lis.append(a)
            ind+=1
            continue
        else:
            s=ind
            while(line[ind].isdigit()):ind+=1
            lis.append(line[s:ind])
            continue
    return lis

def dParen(lis,sind):
    cnt = 1
    s = sind
    sind+=1
    while 1:
        if(lis[sind]==")"):
            cnt -= 1
            if(cnt==0):return (s,sind)
        elif(lis[sind]=="("):
            cnt += 1
        sind+=1


           

def eva(lis):
    #print lis
    if(len(lis)==1):return lis[0]
    if("(" in lis):
        (s,e) = dParen(lis,lis.index("("))
        val = eva(lis[s+1:e])
        lis[s:e+1]=[val]
        return eva(lis)
    if("*" in lis or "/" in lis):
        inmin = 0;
        if(("*" in lis)==False):
            inmin = lis.index("/")
        elif(("/" in lis)==False):
            inmin = lis.index("*")
        else:
            inmin = min(lis.index("x"),lis.index("/"))
        if(lis[inmin]=="*"):
            val = int(lis[inmin-1])*int(lis[inmin+1])
            lis[inmin-1:inmin+2]=[val]
        else:
            val = int(lis[inmin-1])/int(lis[inmin+1])
            lis[inmin-1:inmin+2]=[val]
        return eva(lis)
    if("+" in lis or "-" in lis):
        if(("+" in lis)==False):
            inmin = lis.index("-")
        elif(("-" in lis)==False):
            inmin = lis.index("+")
        else:
            inmin = min(lis.index("+"),lis.index("-"))
        if(lis[inmin]=="+"):
            val = int(lis[inmin-1])+int(lis[inmin+1])
            lis[inmin-1:inmin+2]= [val]
        else:
            val = int(lis[inmin-1])-int(lis[inmin+1])
            lis[inmin-1:inmin+2]=[val]
        return eva(lis)
    

n = int(raw_input())
for i in range(n):
    calcu = parse(raw_input())
    #print calcu
    print eva(calcu)

Submission status: Runtime Error

Solution code:
def parse(line):
    lis = []
    ind =0
    while(line[ind]!="="):
        a = line[ind]
        if(a.isdigit()==False):
            lis.append(a)
            ind+=1
            continue
        else:
            s=ind
            while(line[ind].isdigit()):ind+=1
            lis.append(line[s:ind])
            continue
    return lis

def dParen(lis,sind):
    cnt = 1
    s = sind
    sind+=1
    while 1:
        if(lis[sind]==")"):
            cnt -= 1
            if(cnt==0):return (s,sind)
        elif(lis[sind]=="("):
            cnt += 1
        sind+=1


           

def eva(lis):
    #print lis
    if(len(lis)==1):return lis[0]
    if("(" in lis):
        (s,e) = dParen(lis,lis.index("("))
        val = eva(lis[s+1:e])
        lis[s:e+1]=[val]
        return eva(lis)
    if("*" in lis or "/" in lis):
        inmin = 0;
        if(("*" in lis)==False):
            inmin = lis.index("/")
        elif(("/" in lis)==False):
            inmin = lis.index("*")
        else:
            inmin = min(lis.index("x"),lis.index("/"))
        if(lis[inmin]=="*"):
            val = int(lis[inmin-1])*int(lis[inmin+1])
            lis[inmin-1:inmin+2]=[val]
        else:
            val = int(lis[inmin-1])/int(lis[inmin+1])
            lis[inmin-1:inmin+2]=[val]
        return eva(lis)
    if("+" in lis or "-" in lis):
        if(("+" in lis)==False):
            inmin = lis.index("-")
        elif(("-" in lis)==False):
            inmin = lis.index("+")
        else:
            inmin = min(lis.index("+"),lis.index("-"))
        if(lis[inmin]=="+"):
            val = int(lis[inmin-1])+int(lis[inmin+1])
            lis[inmin-1:inmin+2]= [val]
        else:
            val = int(lis[inmin-1])-int(lis[inmin+1])
            lis[inmin-1:inmin+2]=[val]
        return eva(lis)
    

n = int(raw_input())
for i in range(n):
    calcu = parse(raw_input())
    #print calcu
    print eva(calcu)

Submission status: Runtime Error

Solution code:

def parse(line):
    lis = []
    ind =0
    while(line[ind]!="="):
        a = line[ind]
        if(ind==0 and a=="-"):
            s=ind
            ind += 1
            while(line[ind].isdigit()):ind+=1
            lis.append(int(line[s:ind]))
            continue
        if(a.isdigit()==False):
            lis.append(a)
            ind+=1
            continue
        else:
            s=ind
            while(line[ind].isdigit()):ind+=1
            lis.append(line[s:ind])
            continue
    return lis

def dParen(lis,sind):
    cnt = 1
    s = sind
    sind+=1
    while 1:
        if(lis[sind]==")"):
            cnt -= 1
            if(cnt==0):return (s,sind)
        elif(lis[sind]=="("):
            cnt += 1
        sind+=1


           

def eva(lis):
    #print lis
    if(len(lis)==1):return lis[0]
    if("(" in lis):
        (s,e) = dParen(lis,lis.index("("))
        val = eva(lis[s+1:e])
        lis[s:e+1]=[val]
        return eva(lis)
    if("*" in lis or "/" in lis):
        inmin = 0;
        if(("*" in lis)==False):
            inmin = lis.index("/")
        elif(("/" in lis)==False):
            inmin = lis.index("*")
        else:
            inmin = min(lis.index("x"),lis.index("/"))
        if(lis[inmin]=="*"):
            val = int(lis[inmin-1])*int(lis[inmin+1])
            lis[inmin-1:inmin+2]=[val]
        else:
            val = int(lis[inmin-1])/int(lis[inmin+1])
            lis[inmin-1:inmin+2]=[val]
        return eva(lis)
    if("+" in lis or "-" in lis):
        if(("+" in lis)==False):
            inmin = lis.index("-")
        elif(("-" in lis)==False):
            inmin = lis.index("+")
        else:
            inmin = min(lis.index("+"),lis.index("-"))
        if(lis[inmin]=="+"):
            val = int(lis[inmin-1])+int(lis[inmin+1])
            lis[inmin-1:inmin+2]= [val]
        else:
            val = int(lis[inmin-1])-int(lis[inmin+1])
            lis[inmin-1:inmin+2]=[val]
        return eva(lis)
    

n = int(raw_input())
for i in range(n):
    calcu = parse(raw_input())
    #print calcu
    print eva(calcu)

Submission status: Runtime Error

Solution code:
# ????????±?????¬??§??????????????????[l, r)??§??????
def getLR(li):
    l, r = 0, 0
    for i in range(len(li)):
        if li[i] == "(":
            l = i
        if li[i] == ")":
            r = i + 1
            return l, r
    return l, r

# li????¨?????????????????????????(li?????¬??§???????????????)
def calc(li):
    # *, / ?????????
    t_li = []
    while True:
        for i in range(len(li) - 2):
            if li[i + 1] == "*":
                t_li = li[:i] + [li[i] * li[i + 2]] + li[i + 3:]
                li = list(t_li)
                break
            elif li[i + 1] == "/":
                t_li = li[:i] + [li[i] // li[i + 2]] + li[i + 3:]
                li = list(t_li)
                break
        else:
            # ??´??°??????????????°????????????????????????
            break

    # +, - ?????????
    while True:
        for i in range(len(li) - 2):
            if li[i + 1] == "+":
                t_li = li[:i] + [li[i] + li[i + 2]] + li[i + 3:]
                li = list(t_li)
                break
            elif li[i + 1] == "-":
                t_li = li[:i] + [li[i] - li[i + 2]] + li[i + 3:]
                li = list(t_li)
                break
        else:
            # ??´??°??????????????°????????????????????????
            break

    return t_li


n = int(input())
for _ in range(n):
    s = input()[:-1]

    # ??°?????¨?¨????????????????????????? ("#"?????????)
    s = "#(" + s + ")#"
    li = []
    number = ""
    for i in range(len(s)):
        if s[i].isdigit():
            number += s[i]
        else:
            if number != "":
                li.append(int(number))
                number = ""
            li.append(s[i])

    # ??¬??§??????????????±?????¨??????????????????????????????
    while True:
        # print(li)
        l, r = getLR(li)

        # ??¬??§????????????????????°??????
        if r == 0:
            break

        li = li[:l] + calc(li[l + 1 : r - 1]) + li[r:]

    print(li[1])

Submission status: Runtime Error

Solution code:
def getLR(li):
    l, r = 0, 0
    for i in range(len(li)):
        if li[i] == "(":
            l = i
        if li[i] == ")":
            r = i + 1
            return l, r
    return l, r

def calc(li):
    # *, /
    t_li = []
    while True:
        for i in range(len(li) - 2):
            if li[i + 1] == "*":
                t_li = li[:i] + [li[i] * li[i + 2]] + li[i + 3:]
                li = list(t_li)
                break
            elif li[i + 1] == "/":
                t_li = li[:i] + [li[i] // li[i + 2]] + li[i + 3:]
                li = list(t_li)
                break
        else:
            # no update
            break

    # +, -
    while True:
        for i in range(len(li) - 2):
            if li[i + 1] == "+":
                t_li = li[:i] + [li[i] + li[i + 2]] + li[i + 3:]
                li = list(t_li)
                break
            elif li[i + 1] == "-":
                t_li = li[:i] + [li[i] - li[i + 2]] + li[i + 3:]
                li = list(t_li)
                break
        else:
            break

    return t_li


n = int(input())
for _ in range(n):
    s = input()[:-1]

    s = "#(" + s + ")#"
    li = []
    number = ""
    for i in range(len(s)):
        if s[i].isdigit():
            number += s[i]
        else:
            if number != "":
                li.append(int(number))
                number = ""
            li.append(s[i])

    while True:
        l, r = getLR(li)

        if r == 0:
            break

        li = li[:l] + calc(li[l + 1 : r - 1]) + li[r:]

    print(li[1])

Submission status: Runtime Error

Solution code:
def f1(line):
    p = None
    q = None
    for i, s in enumerate(line):
        if s == '(':
            p = i
        elif s == ')':
            q = i
        if q:
            break
    else:
        return f2(line)
    before = line[:p]
    after = line[q + 1:]
    x = f2(line[p + 1:q])
    return f1(before + str(x) + after)


def f2(f_line):
    foo = []
    digit = ''
    for x in f_line:
        if x.isdigit():
            digit += x
        else:
            foo.append(int(digit))
            foo.append(x)
            digit = ''
    foo.append(int(digit))
    return f3(foo, 'first')


def f3(foo, flg):
    if len(foo) == 1:
        return foo[0]
    target = None
    for i, fo in enumerate(foo):
        if flg == 'first':
            target = f4(foo, fo, i)
        elif flg == 'second':
            target = f5(foo, fo, i)
        if target:
            break
    else:
        flg = 'second'
        return f3(foo, flg)
    foo = foo[:i-1] + [target] + foo[i+2:]
    return f3(foo, flg)


def f4(foo, fo, i):
    target = None
    if fo == '*':
        target = foo[i-1] * foo[i+1]
    elif fo == '/':
        target = int(foo[i-1] / foo[i+1])
    return target


def f5(foo, fo, i):
    target = None
    if fo == '+':
        target = foo[i-1] + foo[i+1]
    elif fo == '-':
        target = int(foo[i-1] - foo[i+1])
    return target


for _ in range(int(input())):
    ans = f1(input())
    print(ans)

Submission status: Runtime Error

Solution code:
def f1(line):
    p = None
    q = None
    for i, s in enumerate(line):
        if s == '(':
            p = i
        elif s == ')':
            q = i
        if q:
            break
    else:
        return f2(line)
    before = line[:p]
    after = line[q + 1:]
    x = f2(line[p + 1:q])
    return f1(before + str(x) + after)


def f2(f_line):
    foo = []
    digit = ''
    for x in f_line:
        if x.isdigit():
            digit += x
        else:
            foo.append(int(digit))
            foo.append(x)
            digit = ''
    foo.append(int(digit))
    return f3(foo, 'first')


def f3(foo, flg):
    if len(foo) == 1:
        return foo[0]
    target = None
    for i, fo in enumerate(foo):
        if flg == 'first':
            target = f4(foo, fo, i)
        elif flg == 'second':
            target = f5(foo, fo, i)
        if target:
            break
    else:
        flg = 'second'
        return f3(foo, flg)
    foo = foo[:i-1] + [target] + foo[i+2:]
    return f3(foo, flg)


def f4(foo, fo, i):
    target = None
    if fo == '*':
        target = foo[i-1] * foo[i+1]
    elif fo == '/':
        target = int(foo[i-1] / foo[i+1])
    return target


def f5(foo, fo, i):
    target = None
    if fo == '+':
        target = foo[i-1] + foo[i+1]
    elif fo == '-':
        target = int(foo[i-1] - foo[i+1])
    return target


for _ in range(int(input())):
    input_line = input()
    ans = f1(input_line[:-1])
    print(ans)

Submission status: Runtime Error

Solution code:
def f1(line):
    p = None
    q = None
    for i, s in enumerate(line):
        if s == '(':
            p = i
        elif s == ')':
            q = i
        if q:
            break
    else:
        return f2(line)
    before = line[:p]
    after = line[q + 1:]
    x = f2(line[p + 1:q])
    return f1(before + str(x) + after)


def f2(f_line):
    foo = []
    digit = ''
    for x in f_line:
        if x.isdigit():
            digit += x
        else:
            foo.append(int(digit))
            foo.append(x)
            digit = ''
    foo.append(int(digit))
    return f3(foo, 'first')


def f3(foo, flg):
    if len(foo) == 1:
        return foo[0]
    target = None
    for i, fo in enumerate(foo):
        if flg == 'first':
            target = f4(foo, fo, i)
        elif flg == 'second':
            target = f5(foo, fo, i)
        if target:
            break
    else:
        flg = 'second'
        return f3(foo, flg)
    foo = foo[:i-1] + [target] + foo[i+2:]
    return f3(foo, flg)


def f4(foo, fo, i):
    target = None
    if fo == '*':
        target = foo[i-1] * foo[i+1]
    elif fo == '/':
        target = int(foo[i-1] / foo[i+1])
    return target


def f5(foo, fo, i):
    target = None
    if fo == '+':
        target = foo[i-1] + foo[i+1]
    elif fo == '-':
        target = foo[i-1] - foo[i+1]
    return target


for _ in range(int(input())):
    ans = f1(input()[:-1])
    print(ans)

Submission status: Runtime Error

Solution code:
inputs=[]
while True:
  try:
    inputs.append(input())
  except EOFError:
    break

for i in inputs:
  a,c=i.split("=")
  a,b=a.split("+")
  # a+b=c
  for x in range(0,10):
    if x==0 and (a[0]=="X" or b[0]=="X" or c[0]=="X"):
        next
    A=a.replace("X",str(x))
    B=b.replace("X",str(x))
    C=c.replace("X",str(x))
    if int(A)+int(B)==int(C):
      print(x)
      break
    if x == 9:
      print("NA")

Submission status: Runtime Error

Solution code:
def calc(eqt):
  l = eqt.split("+",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])+calc(l[1]))
  l = eqt.split("-",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])-calc(l[1]))
  l = eqt.split("*",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])*calc(l[1]))
  l = eqt.split("/",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])//calc(l[1]))
  return (int(eqt))

def unfold_brackets(eqt):
  l = eqt.split(')',maxsplit=1)
  if len(l) == 1:
    return calc(eqt)
  else:
    ll = l[0].rsplit('(',maxsplit=1)
    ll.append(l[1])
    ll[1] = str(calc(ll[1]))
    l="".join(ll)
    return unfold_brackets(l)

datasets=[]
while True:
  try:
    datasets.append(input())
  except EOFError:
    break
for line in datasets:
  if line[-1] != '=':
    continue
  else:
    l = line.split("=",maxsplit=1)[0]
    print(unfold_brackets(l))

Submission status: Runtime Error

Solution code:
def calc(eqt):
  l = eqt.split("+",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])+calc(l[1]))
  l = eqt.split("-",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])-calc(l[1]))
  l = eqt.split("*",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])*calc(l[1]))
  l = eqt.split("/",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])//calc(l[1]))
  return (int(eqt))

def unfold_brackets(eqt):
  l = eqt.split(')',maxsplit=1)
  if len(l) == 1:
    return calc(eqt)
  else:
    ll = l[0].rsplit('(',maxsplit=1)
    ll.append(l[1])
    ll[1] = str(calc(ll[1]))
    l="".join(ll)
    return unfold_brackets(l)

n=int(input())
datasets=[input() for i in range(n)]
for line in datasets:
  l = line.split("=",maxsplit=1)[0]
  print(unfold_brackets(l))

Submission status: Runtime Error

Solution code:
def calc(eqt):
  l = eqt.split("+",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])+calc(l[1]))
  l = eqt.split("-",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])-calc(l[1]))
  l = eqt.split("*",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])*calc(l[1]))
  l = eqt.split("/",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])//calc(l[1]))
  return (int(eqt))

def unfold_brackets(eqt):
  l = eqt.split(')',maxsplit=1)
  if len(l) == 1:
    return calc(eqt)
  else:
    ll = l[0].rsplit('(',maxsplit=1)
    ll.append(l[1])
    ll[1] = str(calc(ll[1]))
    l="".join(ll)
    return unfold_brackets(l)

n=int(input())
datasets=[None]*n
for i in range(0,n):
  datasets[i] = input()
for line in datasets:
  l = line.split("=",maxsplit=1)[0]
  print(unfold_brackets(l))

Submission status: Runtime Error

Solution code:
def calc(eqt):
  l = eqt.split("+",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])+calc(l[1]))
  l = eqt.split("-",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])-calc(l[1]))
  l = eqt.split("*",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])*calc(l[1]))
  l = eqt.split("/",maxsplit=1)
  if len(l) == 2:
    return (calc(l[0])/calc(l[1]))
  return (int(eqt))

def unfold_brackets(eqt):
  l = eqt.split(')',maxsplit=1)
  if len(l) == 1:
    return calc(eqt)
  else:
    ll = l[0].rsplit('(',maxsplit=1)
    ll.append(l[1])
    ll[1] = str(calc(ll[1]))
    l="".join(ll)
    return unfold_brackets(l)

n=int(input())
datasets=[input() for i in range(n)]
for line in datasets:
  l = line.split("=",maxsplit=1)[0]
  print(unfold_brackets(l))