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 calc(eqt): # assuming that eqt has no brackets.
  l = eqt.split("+",maxsplit=1)
  if len(l) == 2: # if eqt has "+", then
    return (calc(l[0])+calc(l[1]))
  l = eqt.split("-",maxsplit=1)
  if len(l) == 2:# if eqt has "-", then
    return (calc(l[0])-calc(l[1]))
  l = eqt.split("*",maxsplit=1)
  if len(l) == 2:# if eqt has "*", then
    return (calc(l[0])*calc(l[1]))
  l = eqt.split("/",maxsplit=1)
  if len(l) == 2:# if eqt has "/", then
    return (calc(l[0])/calc(l[1]))
  return (int(eqt))

def unfold_brackets(eqt): # for example, eqt == "((3+5)*8+2)*2"
  l = eqt.split(')',maxsplit=1)
  if len(l) == 1: # if eqt has no brackets, then
    return calc(eqt)
  else:
    # for example, l == ["((3+5", "*8+2)*2"]
    ll = l[0].rsplit('(',maxsplit=1)
    # ll == ["(","3+5"]
    ll.append(l[1])
    # ll == ["(","3+5","*8+2)*2"]
    ll[1] = str(calc(ll[1]))
    # ll == ["(",8,"*8+2)*2"]
    l="".join(ll)
    # ll == "(8*8+2)*2"
    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): # assuming that eqt has no brackets.
  l = eqt.split("+",maxsplit=1)
  if len(l) == 2: # if eqt has "+", then
    return (calc(l[0])+calc(l[1]))
  l = eqt.split("-",maxsplit=1)
  if len(l) == 2:# if eqt has "-", then
    return (calc(l[0])-calc(l[1]))
  l = eqt.split("*",maxsplit=1)
  if len(l) == 2:# if eqt has "*", then
    return (calc(l[0])*calc(l[1]))
  l = eqt.split("/",maxsplit=1)
  if len(l) == 2:# if eqt has "/", then
    return (calc(l[0])/calc(l[1]))
  return (int(eqt))

def unfold_brackets(eqt): # for example, eqt == "((3+5)*8+2)*2"
  l = eqt.split(')',maxsplit=1)
  if len(l) == 1: # if eqt has no brackets, then
    return calc(eqt)
  else:
    # for example, l == ["((3+5", "*8+2)*2"]
    ll = l[0].rsplit('(',maxsplit=1)
    # ll == ["(","3+5"]
    ll.append(l[1])
    # ll == ["(","3+5","*8+2)*2"]
    ll[1] = str(calc(ll[1]))
    # ll == ["(",8,"*8+2)*2"]
    l="".join(ll)
    # ll == "(8*8+2)*2"
    return unfold_brackets(l)

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

Submission status: Runtime Error

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

def unfold_brackets(eqt): # for example, eqt == "((3+5)*8+2)*2"
  l = eqt.split(')',maxsplit=1)
  if len(l) == 1: # if eqt has no brackets, then
    return calc(eqt)
  else:
    # for example, l == ["((3+5", "*8+2)*2"]
    ll = l[0].rsplit('(',maxsplit=1)
    # ll == ["(","3+5"]
    ll.append(l[1])
    # ll == ["(","3+5","*8+2)*2"]
    ll[1] = str(calc(ll[1]))
    # ll == ["(",8,"*8+2)*2"]
    l="".join(ll)
    # ll == "(8*8+2)*2"
    return unfold_brackets(l)

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

Submission status: Runtime Error

Solution code:
#n=int(input())

def lastfind(s,x):
    n=len(s)
    s_rev=s[::-1]
    t=s_rev.find(x)
    return n-t-1
def doublefind(s,x,y):
    if x in s:
        p=s.find(x)
    else:
        p=len(s)+10
    if y in s:
        q=s.find(y)
    else:
        q=len(s)+10
    
    if p<=q and p<len(s)+5:
        return [p,x]
    elif q<len(s)+5:
        return [q,y]
    else:
        return 0

def calculator(s):
    if s=="":
        return 0
    
    try:
        return int(s)
    except:
        try:
            x=doublefind(s,"+","-")
            if x[1]=="+":
                return calculator(s[:x[0]:])+calculator(s[x[0]+1::])
            else:
                return calculator(s[:x[0]:])-calculator(s[x[0]+1::])
        except:
            x=doublefind(s,"*","/")
            if x[1]=="*":
                return calculator(s[:x[0]:])*calculator(s[x[0]+1::])
            else:
                return calculator(s[:x[0]:])/calculator(s[x[0]+1::])
def remove_brackets(s):
    if s[0]=="(" and s[-1]==")":
        return s[1:-1:]
    else:
        return s
def calc(s):
    while "(" in s:
        closec=s.find(")")
        openc=lastfind(s[:closec:],"(")
        s=s[:openc:]+str(calculator(s[openc+1:closec:]))+s[closec+1::]
    return calculator(s)
        
n=int(input())
for count in range(n):
    s=input()
    print(int(calc(s[:-1:])))

Submission status: Runtime Error

Solution code:
#n=int(input())

def lastfind(s,x):
    n=len(s)
    s_rev=s[::-1]
    t=s_rev.find(x)
    return n-t-1
def doublefind(s,x,y):
    if x in s:
        p=s.find(x)
    else:
        p=len(s)+10
    if y in s:
        q=s.find(y)
    else:
        q=len(s)+10
    
    if p<=q and p<len(s)+5:
        return [p,x]
    elif q<len(s)+5:
        return [q,y]
    else:
        return 0

def calculator(s):
    if s=="":
        return 0
    
    try:
        return int(s)
    except:
        try:
            x=doublefind(s,"+","-")
            if x[1]=="+":
                return calculator(s[:x[0]:])+calculator(s[x[0]+1::])
            else:
                return calculator(s[:x[0]:])-calculator(s[x[0]+1::])
        except:
            x=doublefind(s,"*","/")
            if x[1]=="*":
                return calculator(s[:x[0]:])*calculator(s[x[0]+1::])
            else:
                return calculator(s[:x[0]:])/calculator(s[x[0]+1::])

def calc(s):
    while "(" in s:
        closec=s.find(")")
        openc=lastfind(s[:closec:],"(")
        t=s[:openc:]+str(calculator(s[openc+1:closec:]))+s[closec+1::]
        s=t
    return calculator(s)
        
n=int(input())
for count in range(n):
    s=input()
    print(int(calc(s[:-1:])))

Submission status: Runtime Error

Solution code:
#n=int(input())

def lastfind(s,x):
    n=len(s)
    s_rev=s[::-1]
    t=s_rev.find(x)
    return n-t-1
def doublefind(s,x,y):
    if x in s:
        p=lastfind(s,x)
    else:
        p=-1
    if y in s:
        q=lastfind(s,y)
    else:
        q=-1
    
    if p==-1 and q==-1:
        return 0
    elif p<=q:
        return [q,y]
    else:
        return [p,x]

def calculator(s):
    if s=="":
        return 0
    
    try:
        return int(s)
    except:
        try:
            x=doublefind(s,"+","-")
            if x[1]=="+":
                return calculator(s[:x[0]:])+calculator(s[x[0]+1::])
            else:
                return calculator(s[:x[0]:])-calculator(s[x[0]+1::])
        except:
            x=doublefind(s,"*","/")
            if x[1]=="*":
                return calculator(s[:x[0]:])*calculator(s[x[0]+1::])
            else:
                return calculator(s[:x[0]:])/calculator(s[x[0]+1::])

def calc(s):
    while "(" in s:
        closec=s.find(")")
        openc=lastfind(s[:closec:],"(")
        s=s[:openc:]+str(calculator(s[openc+1:closec:]))+s[closec+1::]
        print (s)
    return calculator(s)
        
n=int(input())
for count in range(n):
    s=input()
    print(int(calc(s[:-1:])))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0109&lang=jp
"""
import sys
import re


def solve(exp):
    exp = exp.replace('=', '')
    exp = exp.replace('/', '//')
    return eval(exp)


def solve2(exp):
    exp = exp.replace('=', '')
    p = re.compile('(-*\d)/(\d)')
    return eval((p.sub(r'int(\1/\2)', exp)))


def main(args):
    n = int(input())
    for _ in range(n):
        expression = input().strip()
        result = solve2(expression)
        print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0109&lang=jp
"""
import sys
import re


def solve(exp):
    exp = exp.replace('=', '')
    exp = exp.replace('/', '//')
    return eval(exp)


def solve2(exp):
    exp = exp.replace('=', '')
    p = re.compile('(\d)/(\d)')
    return eval((p.sub(r'int(\1/\2)', exp)))


def main(args):
    n = int(input())
    for _ in range(n):
        expression = input().strip()
        result = solve2(expression)
        print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0109&lang=jp

"""
import sys
from sys import stdin
import re
input = stdin.readline


class SmartInt(int):
    def __truediv__(self, other):
        sign = 1
        if self.n < 0:
            sign = -1
            self.n *= -1
        return (self.n // other) * sign


def main(args):
    n = int(input())
    for _ in range(n):
        # txt = '4*(8+4+3)='
        txt = input().strip()
        p = re.sub('(\d+)', 'SmartInt(\\1)', txt)
        exp = p[:-1]
        print(eval(exp))


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Runtime Error

Solution code:
n = int(input())
for i in range(n):
    eq = input().replace("=","")
    print(eval(eq))

Submission status: Runtime Error

Solution code:
n = int(input())
for i in range(n):
    eq = input().replace("/","//")
    print(eval(eq))

Submission status: Runtime Error

Solution code:
n = int(input())
for i in range(n):
    eq = input().replace("/","//").replace("=","")
    print(eval(eq))

Submission status: Runtime Error

Solution code:
import re
#from me.io import dup_file_stdin

#@dup_file_stdin
def solve():
    for _ in range(int(sys.stdin.readline())):
        expr = sys.stdin.readline()[:-1].strip("=")
        expr = re.sub(".d+","",expr)
        print(eval(expr.replace("/","//")))
 
solve()

Submission status: Runtime Error

Solution code:
# coding: utf-8

# Convert String to List
def String2List(s):
    L = []; tmp = ""
    for i in s:
        if i.isdigit():
            tmp += i
        else:
            if tmp != "":
                L.append(tmp)
                tmp = ""
            L.append(i)
    if tmp != "":
        L.append(tmp)

    return L

# generate Reverse Polish Notation
def Generate_RPN(L):
    S, L2 = [], []
    table = {"*": 1, "/": 1, "+": 0, "-": 0, "(": -1, ")": -1}
    for i in L:
        if i.isdigit():
            L2.append(i)
        elif i == "(":
            S.append(i)
        elif i == ")":
            while S[-1] != "(":
                L2.append(S.pop())
            S.pop()
        else:
            while len(S) != 0 and (table[S[-1]] >= table[i]):
                L2.append(S.pop())
            S.append(i)

    while len(S) != 0:
        L2.append(S.pop())

    return L2

def Calculate_RPN(L):
    St = []
 
    for i in L:
        if i == '+':
            St.append(int(St.pop()) + int(St.pop()))
        elif i == '-':
            St.append(-int(St.pop()) + int(St.pop()))
        elif i == '*':
            St.append(int(St.pop()) * int(St.pop()))
        elif i == '/':
            a = int(St.pop())
            b = float(St.pop())
            St.append(b/a)
        else:
            St.append(i)
 
    return St[0]

n = int(raw_input())

for _ in xrange(n):
    s = raw_input()
    print Calculate_RPN(Generate_RPN(String2List(s)))

Submission status: Runtime Error

Solution code:
# coding: utf-8

# Convert String to List
def String2List(s):
    L = []; tmp = ""
    for i in s:
        if i.isdigit():
            tmp += i
        else:
            if tmp != "":
                L.append(tmp)
                tmp = ""
            L.append(i)
    if tmp != "":
        L.append(tmp)

    return L

# generate Reverse Polish Notation
def Generate_RPN(L):
    S, L2 = [], []
    table = {"*": 1, "/": 1, "+": 0, "-": 0, "(": -1, ")": -1}
    for i in L:
        if i.isdigit():
            L2.append(i)
        elif i == "(":
            S.append(i)
        elif i == ")":
            while S[-1] != "(":
                L2.append(S.pop())
            S.pop()
        else:
            while len(S) != 0 and (table[S[-1]] >= table[i]):
                L2.append(S.pop())
            S.append(i)

    while len(S) != 0:
        L2.append(S.pop())

    return L2

def Calculate_RPN(L):
    St = []
 
    for i in L:
        if i == '+':
            St.append(int(St.pop()) + int(St.pop()))
        elif i == '-':
            St.append(-int(St.pop()) + int(St.pop()))
        elif i == '*':
            St.append(int(St.pop()) * int(St.pop()))
        elif i == '/':
            a = int(St.pop())
            b = float(St.pop())
            St.append(b/a)
        else:
            St.append(i)
 
    return St[0]


n = int(raw_input())

for i in xrange(n):
    s = raw_input()
    print Calculate_RPN(Generate_RPN(String2List(s)))

Submission status: Runtime Error

Solution code:
def ReversePolishNotation(string):

    priority = {"Sentinel": 0, "(": 0, "+": 1, "-": 1, "*": 2, "/": 2}

    stack = []
    signStack = ["Sentinel"]

    inputCountent = string[:-1]

    for item in string[:-1]:
        if item == "(":
            signStack.append(item)
        elif item == ")":
            while signStack[-1] != "(":
                stack.append(signStack.pop())
            signStack.pop()
        else:
            if item in priority.keys():
                if priority[signStack[-1]] < priority[item]:
                    signStack.append(item)
                else:
                    top = signStack.pop()
                    stack.append(top)
                    signStack.append(item)
            else:
                stack.append(item)

    while signStack[-1] != "Sentinel":
        stack.append(signStack.pop())

    return stack


def Calculate(formulaList):

    signs = ["+", "-", "*", "/"]

    stack = []

    for item in formulaList:

        if item not in signs:
            stack.append(item)
        else:
            num1 = int(stack.pop())
            num2 = int(stack.pop())

            if item == "+":
                result = num2 + num1
            elif item == "-":
                result = num2 - num1
            elif item == "*":
                result = num2 * num1
            elif item == "/":
                result = num2 / num1

            stack.append(result)

    return stack[0]


inputCount = int(input())

for lp in range(inputCount):
    formula = input()

    rpn = ReversePolishNotation(formula)
    result = Calculate(rpn)

    print(result)

Submission status: Runtime Error

Solution code:
def ReversePolishNotation(string):

    priority = {"Sentinel": 0, "(": 0, "+": 1, "-": 1, "*": 2, "/": 2}

    stack = []
    signStack = ["Sentinel"]

    for item in string[:-1]:
        if item == "(":
            signStack.append(item)
        elif item == ")":
            while signStack[-1] != "(":
                stack.append(signStack.pop())
            signStack.pop()
        else:
            if item in priority.keys():
                if priority[signStack[-1]] < priority[item]:
                    signStack.append(item)
                else:
                    top = signStack.pop()
                    stack.append(top)
                    signStack.append(item)
            else:
                stack.append(item)

    while signStack[-1] != "Sentinel":
        stack.append(signStack.pop())

    return stack


def Calculate(formulaList):

    signs = ["+", "-", "*", "/"]

    stack = []

    for item in formulaList:

        if item not in signs:
            stack.append(item)
        else:
            num1 = int(stack.pop())
            num2 = int(stack.pop())

            if item == "+":
                result = num2 + num1
            elif item == "-":
                result = num2 - num1
            elif item == "*":
                result = num2 * num1
            elif item == "/":
                result = num2 / num1

            stack.append(result)

    return int(stack[0])


inputCount = int(input())

for lp in range(inputCount):
    formula = input()

    rpn = ReversePolishNotation(formula)
    answer = Calculate(rpn)

    print(answer)

Submission status: Runtime Error

Solution code:
def ReversePolishNotation(string):

    priority = {"Sentinel": 0, "(": 0, "+": 1, "-": 1, "*": 2, "/": 2}

    stack = []
    signStack = ["Sentinel"]

    for item in string[:-1]:
        if item == "(":
            signStack.append(item)
        elif item == ")":
            while signStack[-1] != "(":
                stack.append(signStack.pop())
            signStack.pop()
        else:
            if item in priority.keys():
                if priority[signStack[-1]] < priority[item]:
                    signStack.append(item)
                else:
                    top = signStack.pop()
                    stack.append(top)
                    signStack.append(item)
            else:
                stack.append(item)

    while signStack[-1] != "Sentinel":
        stack.append(signStack.pop())

    return stack


def Calculate(formulaList):

    signs = ["+", "-", "*", "/"]

    stack = []

    for item in formulaList:

        if item not in signs:
            stack.append(item)
        else:
            num1 = int(stack.pop())
            num2 = int(stack.pop())

            result = 0

            if item == "+":
                result = num2 + num1
            elif item == "-":
                result = num2 - num1
            elif item == "*":
                result = num2 * num1
            else:
                result = num2 / num1

            stack.append(result)
        print(stack)
        print(item)

    return int(stack[0])


inputCount = int(input())

for lp in range(inputCount):
    formula = input()

    rpn = ReversePolishNotation(formula)
    answer = Calculate(rpn)

Submission status: Runtime Error

Solution code:
def ReversePolishNotation(string):

    priority = {"Sentinel": 0, "(": 0, "+": 1, "-": 1, "*": 2, "/": 2}

    stack = []
    signStack = ["Sentinel"]

    for item in string[:-1]:
        if item == "(":
            signStack.append(item)
        elif item == ")":
            while signStack[-1] != "(":
                stack.append(signStack.pop())
            signStack.pop()
        else:
            if item in priority.keys():
                if priority[signStack[-1]] < priority[item]:
                    signStack.append(item)
                else:
                    top = signStack.pop()
                    stack.append(top)
                    signStack.append(item)
            else:
                stack.append(item)

    while signStack[-1] != "Sentinel":
        stack.append(signStack.pop())

    return stack


def Calculate(formulaList):

    signs = ["+", "-", "*", "/"]

    stack = []

    for item in formulaList:

        if item not in signs:
            stack.append(item)
        else:
            num1 = 0
            num2 = 0

            result = 0

            if item == "+":
                result = num2 + num1
            elif item == "-":
                result = num2 - num1
            elif item == "*":
                result = num2 * num1
            else:
                result = num2 / num1

            stack.append(result)

    return int(stack[0])


inputCount = int(input())

for lp in range(inputCount):
    formula = input()

    rpn = ReversePolishNotation(formula)
    answer = Calculate(rpn)

    print(answer)

Submission status: Runtime Error

Solution code:
def ReversePolishNotation(string):

    priority = {"Sentinel": 0, "(": 0, "+": 1, "-": 1, "*": 2, "/": 2}

    stack = []
    signStack = ["Sentinel"]

    for item in string[:-1]:
        if item == "(":
            signStack.append(item)
        elif item == ")":
            while signStack[-1] != "(":
                stack.append(signStack.pop())
            signStack.pop()
        else:
            if item in priority.keys():
                if priority[signStack[-1]] < priority[item]:
                    signStack.append(item)
                else:
                    top = signStack.pop()
                    stack.append(top)
                    signStack.append(item)
            else:
                stack.append(item)

    while signStack[-1] != "Sentinel":
        stack.append(signStack.pop())

    return stack


def Calculate(formulaList):

    signs = ["+", "-", "*", "/"]

    stack = []

    for item in formulaList:

        if item not in signs:
            stack.append(item)
        else:
            num1 = int(stack.pop())
            num2 = int(stack.pop())

            result = 0

            if item == "+":
                result = num2 + num1
            elif item == "-":
                result = num2 - num1
            elif item == "*":
                result = num2 * num1
            else:
                result = num2 / num1

            stack.append(result)

    return int(stack[0])


inputCount = int(input())

for lp in range(inputCount):
    formula = input()

    rpn = ReversePolishNotation(formula)
    answer = Calculate(rpn)

    print(str(answer))

Submission status: Runtime Error

Solution code:
def ReversePolishNotation(string):

    priority = {"Sentinel": 0, "(": 0, "+": 1, "-": 1, "*": 2, "/": 2}

    stack = []
    signStack = ["Sentinel"]

    for item in string[:-1]:
        if item == "(":
            signStack.append(item)
        elif item == ")":
            while signStack[-1] != "(":
                stack.append(signStack.pop())
            signStack.pop()
        else:
            if item in priority.keys():
                if priority[signStack[-1]] < priority[item]:
                    signStack.append(item)
                else:
                    top = signStack.pop()
                    stack.append(top)
                    signStack.append(item)
            else:
                stack.append(item)

    while signStack[-1] != "Sentinel":
        stack.append(signStack.pop())

    return stack


def Calculate(formulaList):

    signs = ["+", "-", "*", "/"]

    stack = []

    for item in formulaList:

        if item not in signs:
            stack.append(item)
        else:
            num1 = int(stack.pop())
            num2 = int(stack.pop())

            result = 0

            if item == "+":
                result = num2 + num1
            elif item == "-":
                result = num2 - num1
            elif item == "*":
                result = num2 * num1
            else:
                result = num2 / num1
                result = int(result)

            stack.append(result)

    return int(stack[0])


inputCount = int(input())

for lp in range(inputCount):
    formula = input()

    rpn = ReversePolishNotation(formula)
    answer = Calculate(rpn)

    print(str(answer))

Submission status: Runtime Error

Solution code:
R={"*":2,"/":2,"+":1,"-":1,"(":0,")":0}
for _ in[0]*int(input()):
 L=[];t=''
 for e in input()[:-1]:
  if e.isdigit():t+=e
  else:
   if t:L+=[t];t=''
   L+=e
 if t:L+=[t]
 P,S=[],[]
 for i in L:
  if"("==i:S+=i
  elif")"==i:
   while"("!=S[-1]:P+=S.pop()
   S.pop()
  elif i in R:
   while S and R[S[-1]]>=R[i]:P+=S.pop()
   S+=i
  else:P+=[i]
 while S:P+=S.pop()
 for x in P:
  S+=[str(eval(s.pop(-2)+p+s.pop()))if x in"+-*/"else x]
 print(*S)

Submission status: Runtime Error

Solution code:
R={"*":2,"/":2,"+":1,"-":1,"(":0,")":0}
for _ in[0]*int(input()):
 L=[];t=''
 for e in input()[:-1]:
  if e.isdigit():t+=e
  else:
   if t:L+=[t];t=''
   L+=e
 if t:L+=[t]
 P,S=[],[]
 for i in L:
  if"("==i:S+=i
  elif")"==i:
   while"("!=S[-1]:P+=S.pop()
   S.pop()
  elif i in R:
   while S and R[S[-1]]>=R[i]:P+=S.pop()
   S+=i
  else:P+=[i]
 while S:P+=S.pop()
 for x in P:
  S+=[str(eval(S.pop(-2)+p+S.pop()))if x in"+-*/"else x]
 print(*S)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
# 写経した
import re
class Num:
    def __str__(self):
        return str(self.x)
    def __init__(self, value):
        self.x = value
    def __add__(self, value):
        return o(self.x + value.x)
    def __sub__(self, value):
        return o(self.x - value.x)
    def __mul__(self, value):
        return o(self.x * value.x)
    def __truediv__(self, value):
        return o(int(self.x / value.x))
     
N = int(input())
for i in range(N):
    s = input()[:-1]
    s = re.sub(r'(\d+)',r'Num(\1)',s)
    print(eval(s))

Submission status: Runtime Error

Solution code:
from collections import deque
def eva(l, r, op):
    if op == "+":
        return l + r
    elif op == "-":
        return l - r
    elif op == "*":
        return l * r
    elif op == "/":
        return l // r


def calc(exp):
    print("calculate",exp)
    i = 0
    num = deque()
    ops = deque()
    ope = ""
    while i < len(exp):
        print(num, ope, exp[i])
        if exp[i] == '(':
            end = exp[i + 1:].index(")")
            num.append(calc(exp[i + 1:i + 1 + end]))
            i += end
            if ope:
                num.append(eva(num.pop(), num.pop(), ope))
                ope = ""
        if exp[i].isnumeric():
            num.append(int(exp[i]))
            if ope:
                num.append(eva(num.pop(), num.pop(), ope))
                ope = ""
        elif exp[i] in ["*", "/"]:
            ope = exp[i]
        elif exp[i] in ["+", "-"]:
            ops.append(exp[i])
        elif exp[i] == "=":
            break
        i += 1
    while len(ops) != 0:
        l = num.popleft()
        r = num.popleft()
        num.appendleft(eva(l,r,ops.popleft()))
    print(f'function end, return {num[0]}')
    return num[0]


n = int(input())
for i in range(n):
    exp = input()
    print(calc(exp))

# N = int(input())
# for i in range(N):
#     print(int(eval(input().replace("/", "//").strip("="))))

Submission status: Runtime Error

Solution code:
from collections import deque
def eva(l, r, op):
    if op == "+":
        return l + r
    elif op == "-":
        return l - r
    elif op == "*":
        return l * r
    elif op == "/":
        return l // r


def calc(exp):
    i = 0
    num = deque()
    ops = deque()
    ope = ""
    while i < len(exp):
        if exp[i] == '(':
            end = exp[i + 1:].index(")")
            num.append(calc(exp[i + 1:i + 1 + end]))
            i += end
            if ope:
                num.append(eva(num.pop(), num.pop(), ope))
                ope = ""
        if exp[i].isnumeric():
            num.append(int(exp[i]))
            if ope:
                num.append(eva(num.pop(), num.pop(), ope))
                ope = ""
        elif exp[i] in ["*", "/"]:
            ope = exp[i]
        elif exp[i] in ["+", "-"]:
            ops.append(exp[i])
        elif exp[i] == "=":
            break
        i += 1
    while len(ops) != 0:
        l = num.popleft()
        r = num.popleft()
        num.appendleft(eva(l,r,ops.popleft()))
    return num[0]


n = int(input())
for i in range(n):
    exp = input()
    print(calc(exp))

Submission status: Runtime Error

Solution code:
from collections import deque
def eva(l, r, op):
    if op == "+":
        return l + r
    elif op == "-":
        return l - r
    elif op == "*":
        return l * r
    elif op == "/":
        return l // r


def calc(exp):
    i = 0
    num = deque()
    ops = deque()
    ope = ""
    while i < len(exp):
        if exp[i] == '(':
            end = exp[i:].rfind(")")
            num.append(calc(exp[i+1:i+end]))
            i += end + 1
            if ope:
                l = num.pop()
                r = num.pop()
                num.append(eva(l, r, ope))
                ope = ""
        elif exp[i].isnumeric():
            num.append(int(exp[i]))
            if ope:
                num.append(eva(num.pop(), num.pop(), ope))
                ope = ""
        elif exp[i] in ["*", "/"]:
            ope = exp[i]
        elif exp[i] in ["+", "-"]:
            ops.append(exp[i])
        elif exp[i] == "=":
            break
        i += 1
    while len(ops) != 0:
        l = num.popleft()
        r = num.popleft()
        num.appendleft(eva(l,r,ops.popleft()))
    return num[0]


n = int(input())
for i in range(n):
    exp = input()
    print(calc(exp))

Submission status: Runtime Error

Solution code:
from collections import deque
from sys import stderr
from functools import reduce
from operator import add
def f(): return [int(i) for i in input().split()]
def debug(*x, sep=" ", end="\n"):
    for item in x:
        stderr.write(repr(item))
        stderr.write(sep)
    stderr.write(end)


def eva(l, r, op):
    if op == "+":
        return l + r
    elif op == "-":
        return l - r
    elif op == "*":
        return l * r
    elif op == "/":
        return l // r


def calc(exp):
    i = 0
    num = deque()
    ops = deque()
    ope = ""
    while i < len(exp):
        if exp[i] == '(':
            end = exp[i:].rfind(")")
            num.append(calc(exp[i+1:i+end]))
            i += end + 1
            if ope:
                l = num.pop()
                r = num.pop()
                num.append(eva(l, r, ope))
                ope = ""
        elif exp[i].isnumeric():
            num.append(int(exp[i]))
            if ope:
                num.append(eva(num.pop(), num.pop(), ope))
                ope = ""
        elif exp[i] in ["*", "/"]:
            ope = exp[i]
        elif exp[i] in ["+", "-"]:
            ops.append(exp[i])
        elif exp[i] == "=":
            break
        i += 1
    while len(ops) != 0:
        l = num.popleft()
        r = num.popleft()
        num.appendleft(eva(l,r,ops.popleft()))
    
    debug(exp, num)
    return num[0]


n = int(input())
for i in range(n):
    exp = input()
    print(calc(exp))