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 × 10 9 ≤ intermediate results of computation ≤ 10 9  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

Solution (Python):
def digit():
    global S
    global cur
    if S[cur].isdigit():
        n = int(S[cur])
        cur += 1
        return n
def number():
    global S
    L = len(S)
    global cur
    n = digit()
    while (cur < L and S[cur].isdigit()):
        n = n*10 + digit()
    return n
def expression():
    global S
    global cur
    L = len(S)
    a = term()
    while (cur < L and (S[cur] == '+' or S[cur] == '-')):
        op = S[cur]
        cur += 1
        b = term()
        if op == '+':
            a += b
        else:
            a -= b
    return a
import math
def term():
    global S
    global cur
    L = len(S)
    a = factor()
    while (cur < L and (S[cur] == '*' or S[cur] == '/')):
        op = S[cur]
        cur += 1
        b = factor()
        if op == '*':
            a *= b
        else:
            a = math.trunc(a/b)
    return a
def factor():
    global S
    global cur
    if (S[cur] != '('):
        return number()
    else:
        cur += 1
        n = expression()
        if S[cur] == ')':
            cur += 1
            return n

N = int(input().strip())
for _ in range(N):
    S = str(input().strip())
    S = S[:-1]
    cur = 0
    ans = expression()
    print(ans)

Solution (Python):
def f(s):
  while 1:
    b=s.find(")")
    if b<0: return g(s)
    a=s[:b].rfind("(")
    s1=s[a:b+1]
    s=s.replace(s1,f(s1[1:-1]))

def g(s):
  a=""
  f=1
  x=[]
  def F(a,b):
    x.append(a)
    x.append(b)
    return 1,""
  for c in s:
    if c=="=": continue
    elif c in "*/": f,a=F(a,c)
    elif c in "+-":
      if f==1: f,a=0,c
      else: f,a=F(a,c)
    else: f,a=0,a+c
  x.append(a)

  s=x[:]
  x=[]
  f=""
  for e in s:
    if e in "+-": x.append(e)
    elif e in "*/": f=e
    else:
      a=int(e)
      if f=="*": a*=x.pop()
      elif f=="/": a=int(1.0*x.pop()/a)
      x.append(a)
      f=""

  s=x[:]
  x=[]
  f=""
  for e in s:
    if e=="+" or e=="-": f=e
    else:
      a=e
      if f=="+": a+=x.pop()
      elif f=="-": a=x.pop()-a
      x.append(a)
      f=""
  return str(x[0])

n=input()
for _ in [0]*n: 
  s=raw_input()
  print f(s)

Solution (Python):
def f(s):
  while 1:
    b=s.find(")")
    if b<0: return g(s)
    a=s[:b].rfind("(")
    s=s.replace(s[a:b+1],f(s[a+1:b]))

def g(s):
  a=""
  f=1
  x=[]
  def F(a,b):
    x.append(a)
    x.append(b)
    return 1,""
  for c in s:
    if c=="=": continue
    elif c in "*/": f,a=F(a,c)
    elif c in "+-":
      if f==1: f,a=0,c
      else: f,a=F(a,c)
    else: f,a=0,a+c
  x.append(a)

  s=x[:]
  x=[]
  f=""
  for e in s:
    if e in "+-": x.append(e)
    elif e in "*/": f=e
    else:
      a=int(e)
      if f=="*": a*=x.pop()
      elif f=="/": a=int(1.0*x.pop()/a)
      x.append(a)
      f=""

  a,f=0,1
  for e in x:
    if e=="+": f=1
    elif e=="-": f=-1
    else: a+=f*e
  return str(a)

n=input()
for _ in [0]*n:
  print f(raw_input())

Solution (Python):
def f(s):
  while 1:
    b=s.find(")")
    if b<0: return g(s)
    a=s[:b].rfind("(")
    s=s.replace(s[a:b+1],f(s[a+1:b]))

def g(s):
  a=""
  f=1
  x=[]
  def F(a,b):
    x.append(a)
    x.append(b)
    return 1,""
  for c in s:
    if c=="=": continue
    elif c in "*/": f,a=F(a,c)
    elif c in "+-":
      if f==1: f,a=0,c
      else: f,a=F(a,c)
    else: f,a=0,a+c
  x.append(a)

  s=x[:]
  x=[]
  f=""
  for e in s:
    if e in "+-": x.append(e)
    elif e in "*/": f=e
    else:
      a=int(e)
      if f=="*": a*=x.pop()
      elif f=="/": a=int(1.0*x.pop()/a)
      x.append(a)
      f=""
  x="".join(map(str,x))
  return str(eval(x))

n=input()
for _ in [0]*n:
  print f(raw_input())

Solution (Python):


import re

class Num:
    def __init__(this, x):
        this.x = x

    def __str__(this):
        return str(this.x)

    def __add__(this, that):
        return Num(this.x + that.x)

    def __sub__(this, that):
        return Num(this.x - that.x)

    def __truediv__(this, that):
        return Num(int(this.x / that.x))

    def __mul__(this, that):
        return Num(this.x * that.x)

    def __neg__(this):
        return Num(-this.x)

n = int(input())
for _ in range(n):
    expr = input()[0:-1]
    expr = re.sub(r'(\d+)', r'Num(\1)', expr)
    print(eval(expr))

Solution (Python):
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:
            if n == '':
                add = '-'
            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 and o1 % o2 != 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)

Solution (Python):
import re
class c:
	def __str__(self):
		return str(self.x)
	def __init__(self,value):
		self.x=value
	def __add__(self,value):
		return c(self.x+value.x)
	def __sub__(self,value):
		return c(self.x-value.x)
	def __mul__(self,value):
		return c(self.x*value.x)
	def __truediv__(self,value):
		return c(int(self.x/value.x))
n=int(input())
for i in range(n):
	s=input()[:-1]
	s=re.sub(r'(\d+)',r'c(\1)',s)
	print(eval(s))

Solution (Python):
import re
class c(int):
    def __add__(self,n):
        return c(int(self)+int(n))
    def __sub__(self,n):
        return c(int(self)-int(n))
    def __mul__(self,n):
        return c(int(self)*int(n))
    def __truediv__(self,n):
        return c(int(int(self)/int(n)))
  
for _ in range(int(input())):
    print(eval(re.sub(r'(\d+)',r'c(\1)',input()[:-1])))

Solution (Python):


import sys
import os
import math
import re

class Num:
    def __str__(self):
        return str(self.x)

    def __init__(self, value):
        self.x = value

    def __add__(self,value):
        return Num(self.x + value.x)

    def __sub__(self, value):
        return Num(self.x - value.x)

    def __mul__(self, value):
        return Num(self.x * value.x)

    def __truediv__(self,value):
        return Num(int(self.x / value.x))

n = int(input())

for i in range(n):
    command = input().strip()
    command = command.replace('=', '')
    command = re.sub(r'(\d+)', r'Num(\1)', command)
    print(eval(command))


"""
>>> math.floor(0.5)
0
>>> -1 // 2
-1
>>> int(0.5)
0
>>> int(-0.5)
0
"""

Solution (Python):
def String2List(s):
    L = []
    flag = True
    l = len(s)
    for i in range(l):
        if s[i].isdigit() and flag:
            t = ""
            j = 0
            while s[i+j].isdigit():
                t += s[i+j]
                if i+j == l-1:
                    break
                j += 1
            L.append(t)
            flag = False

        elif not s[i].isdigit():
            L.append(s[i])
            flag = True

    return L


def RPN_list(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 RPN_cul(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 range(N):
    s = raw_input()
    L = String2List(s[:-1])
    L = RPN_list(L)
    print int(RPN_cul(L))

Solution (Python):
def String2List(s):
    L = []
    flag = True
    l = len(s)
    for i in range(l):
        if s[i].isdigit() and flag:
            t = ""
            j = 0
            while s[i+j].isdigit():
                t += s[i+j]
                if i+j == l-1:
                    break
                j += 1
            L.append(t)
            flag = False
 
        elif not s[i].isdigit():
            L.append(s[i])
            flag = True
 
    return L
 

def RPN_list(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 RPN_cal(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 range(N):
    s = raw_input()
    L = String2List(s[:-1])
    L = RPN_list(L)
    print int(RPN_cal(L))

Solution (Python):
def String2List(s):
    L = []
    flag = True
    l = len(s)
    for i in range(l):
        if s[i].isdigit() and flag:
            t = ""
            j = 0
            while s[i+j].isdigit():
                t += s[i+j]
                if i+j == l-1:
                    break
                j += 1
            L.append(t)
            flag = False

        elif not s[i].isdigit():
            L.append(s[i])
            flag = True

    return L


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 range(N):
    s = raw_input()
    L = Generate_RPN(String2List(s[:-1]))
    print int(Calculate_RPN(L))

Solution (Python):
import re

class Num:
    def __init__(self, x):
        self.x = x

    def __str__(self):
        return str(self.x)

    def __add__(self, other):
        return Num(self.x + other.x)

    def __sub__(self, other):
        return Num(self.x - other.x)

    def __truediv__(self, other):
        return Num(int(self.x / other.x))

    def __mul__(self, other):
        return Num(self.x * other.x)

    def __neg__(self):
        return Num(-self.x)

n = int(input())
for _ in range(n):
    expr = input()[0:-1]
    expr = re.sub(r'(\d+)', r'Num(\1)', expr)
    print(eval(expr))

Solution (Python):



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


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[:-1])))

Solution (Python):
import sys


def prec(op):
    if op in "+-":return 1
    if op in "*/":return 2
    raise NotImplementedError()
    
def postFix(expr):
    stack = []
    operators = []
    num = 0
    isdigit = False
    for ch in expr:
        if ch.isdigit():
            isdigit = True
            num*=10
            num+=int(ch)
            continue
        else :
            if isdigit:
                stack.append(num)
                num = 0
            isdigit = False
            
            if ch == ')':
                while len(operators) > 0:
                    op = operators.pop()
                    if op == '(':
                        break
                    else:
                        stack.append(op)
                else:
                    raise ValueError
            elif ch == '(':
                operators.append(ch)
            else:
                while len(operators) > 0 and operators[-1]!='(' and prec(operators[-1]) >= prec(ch):
                    stack.append(operators.pop())
                operators.append(ch)
    if isdigit:
        stack.append(num)
    for op in operators[::-1]:
        if op not in "()":
            stack.append(op)
    return stack
        
def evaluate(stack):
    op = stack.pop()
    if type(op) is int:
        return op;
    else:
        b = evaluate(stack);
        a = evaluate(stack);
        return int(eval(str(a)+op+str(b)))


def solve():
    for _ in range(int(sys.stdin.readline())):
        expr = sys.stdin.readline()[:-1].strip("=")
        print(evaluate(postFix(expr)))
        
solve()

Solution (Python):
def ReversePolishNotation(string):

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

    stack = []
    signStack = []
    isContinue = False

    for item in string[:-1]:

        if str.isdigit(item):
            if not isContinue:
                stack.append(item)
                isContinue = True
            else:
                stack[-1] += item
            continue
        elif item == "(":
            signStack.append(item)
        elif item == ")":
            while signStack[-1] != "(":
                stack.append(signStack.pop())
            signStack.pop()
        else:
            while len(signStack) != 0 and priority[item] <= priority[signStack[-1]]:
                stack.append(signStack.pop())

            signStack.append(item)

        isContinue = False

    while len(signStack) != 0:
        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
            else:
                result = int(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)

Solution (Python):
import re
class c(int):
 def __add__(self,n):return c(int(self)+int(n))
 def __sub__(self,n):return c(int(self)-int(n))
 def __mul__(self,n):return c(int(self)*int(n))
 def __truediv__(self,n):return c(int(int(self)/int(n)))
for _ in[0]*int(input()):print(eval(re.sub(r'(\d+)',r'c(\1)',input()[:-1])))

Solution (Python):
import re
class c(int):
 def __add__(self,n):return c(int(self)+int(n))
 def __sub__(self,n):return c(int(self)-int(n))
 def __mul__(self,n):return c(int(self)*int(n))
 def __truediv__(self,n):return c(int(int(self)/int(n)))
for _ in[0]*int(input()):print(eval(re.sub(r'(\d+)',r'c(\1)',input()[:-1])))

Solution (Python):
import re
class c(int):
 def __add__(self,n):return c(int(self)+int(n))
 def __sub__(self,n):return c(int(self)-int(n))
 def __mul__(self,n):return c(int(self)*int(n))
 def __truediv__(self,n):return c(int(int(self)/int(n)))
for _ in[0]*int(input()):print(eval(re.sub(r'(\d+)',r'c(\1)',input()[:-1])))

Solution (Python):
import re
class c:
 def __init__(self,value):self.x=value
 def __str__(self):return str(self.x)
 def __add__(self,value):return c(self.x+value.x)
 def __sub__(self,value):return c(self.x-value.x)
 def __mul__(self,value):return c(self.x*value.x)
 def __truediv__(self,value):return c(int(self.x/value.x))
for i in[0]*int(input()):print(eval(re.sub(r'(\d+)',r'c(\1)',input()[:-1])))

Solution (Python):
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:
  if x in'+-*/':t=S.pop();S+=[str(int(eval(S.pop()+x+t)))]
  else:S+=[x]
 print(*S)

Solution (Python):
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(int(eval(S.pop(-2)+x+S.pop())))if x in"+-*/"else x]
 print(*S)

Solution (Python):
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(int(eval(S.pop(-2)+x+S.pop())))if x in"+-*/"else x]
 print(*S)

Solution (Python):
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(int(eval(S.pop(-2)+x+S.pop())))if x in"+-*/"else x]
 print(*S)

Solution (Python):
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(int(eval(S.pop(-2)+x+S.pop())))if x in"+-*/"else x]
 print(*S)

Solution (Python):
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(int(eval(S.pop(-2)+x+S.pop())))if x in"+-*/"else x]
 print(*S)

Solution (Python):
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(int(eval(S.pop(-2)+x+S.pop())))if x in"+-*/"else x]
 print(*S)

Solution (Python):
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(int(eval(S.pop(-2)+x+S.pop())))if x in"+-*/"else x]
 print(*S)

Solution (Python):
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(int(eval(S.pop(-2)+x+S.pop())))if x in"+-*/"else x]
 print(*S)

Solution (Python):
def get_input():
    while True:
        try:
            yield ''.join(input())
        except EOFError:
            break


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


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

Nline = int(input())
for ll in range(Nline):

    S = input()
    p = Generate_RPN(String2List(S[0:-1]))
    N = len(p)

    s = []
    for i in range(len(p)):
        if p[i] == "+":
            a = int(s.pop())
            b = int(s.pop())
            s.append(str(b+a))
        elif p[i] == "-":
            a = int(s.pop())
            b = int(s.pop())
            s.append(str(b-a))
        elif p[i] == "*":
            a = int(s.pop())
            b = int(s.pop())
            s.append(str(b*a))
        elif p[i] == "/":
            a = int(s.pop())
            b = int(s.pop())
            s.append(str(int(b/a)))
        else:
            s.append(p[i])
    print(s[0])

Solution (Python):
import re
class o:
    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'o(\1)',s)
    print(eval(s))

Solution (Python):



INF = 1000000010
LEFT  = INF+1
RIGHT = INF+2
PLUS  = INF+3
MINUS = INF+4
MUL   = INF+5
DIV   = INF+6
token = { '+':PLUS, '-':MINUS, '*':MUL, '/':DIV }
rank = { PLUS:2, MINUS:2, MUL:3, DIV:3, LEFT:1, RIGHT:1 }

S, top = [0]*200, 0
Q, end = [0]*200, 0

def getInt():
	global id
	global buf
	k = ''
	while buf[id] >= '0' and buf[id] <= '9':
		k += buf[id]
		id += 1
	return int(k)

n = int(input())
for i in range(n):
	buf = list(input())
	id, f, top, end = 0, True, 0, 0
	while True:
		if buf[id] == '=':
			while top > 0:
				top -= 1
				Q[end] = S[top]
				end += 1
			break;
		if buf[id] == '-' and f and buf[id+1] >= '0' and buf[id+1] <= '9':
			id += 1
			Q[end] = -getInt()
			end += 1
			f = False
			continue
		
		f = False
		if buf[id] >= '0' and buf[id] <= '9':
			Q[end] = getInt()
			end += 1
		elif buf[id] == ')':
			while S[top - 1] != LEFT:
				top -= 1
				Q[end] = S[top]
				end += 1
			top -= 1
			id += 1
		elif buf[id] == '(':
			S[top] = LEFT
			top += 1
			id += 1
			f = True
		else:
			k = token[buf[id]]
			id += 1
			while top > 0:
				if rank[k] <= rank[S[top-1]]:
					top -= 1
					Q[end] = S[top];
					end += 1
				else: break
			S[top] = k;
			top += 1

	top = 0
	for i in range(end):
		k = Q[i]
		if k > INF:
			d1, d2 = S[top-1], S[top-2]
			top -= 2
			if k == PLUS: d2 += d1
			elif k == MINUS: d2 -= d1
			elif k == MUL: d2 *= d1
			else:
				if (d2 > 0 and d1 < 0) or (d2 < 0 and d1 > 0):
					d2 //= -d1
					d2 = -d2
				else: d2 //= d1
			S[top] = d2
		else: S[top] = k
		top += 1
	print(S[top-1])

Solution (Python):


import re
class Num:
    def __str__(self):
        return str(self.x)
    def __init__(self, value):
        self.x = value
    def __add__(self, value):
        return Num(self.x + value.x)
    def __sub__(self, value):
        return Num(self.x - value.x)
    def __mul__(self, value):
        return Num(self.x * value.x)
    def __truediv__(self, value):
        return Num(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))

Solution (Python):
pos = 0
def number(s):
	global pos
	x = pos
	if s[pos] == '-' or s[pos] == '+':
		pos += 1
	while s[pos].isdigit():
		pos += 1
	return int(s[x:pos])
expression = None
def factor(s):
	global pos
	if s[pos] == '(':
		pos += 1
		result = expression(s)
		pos += 1
		return result
	else:
		return number(s)
def term(s):
	global pos
	result = factor(s)
	while True:
		if s[pos] == '*':
			pos += 1
			result *= factor(s)
		elif s[pos] == '/':
			pos += 1
			x = factor(s)
			result = int(abs(result) / abs(x)) * cmp(x, 0) * cmp(result, 0)
		else:
			break
	return result
def _expression(s):
	global pos
	result = term(s)
	while True:
		if s[pos] == '+':
			pos += 1
			result += term(s)
		elif s[pos] == '-':
			pos += 1
			result -= term(s)
		else:
			break
	return result
expression = _expression

for i in xrange(input()):
	pos = 0
	print expression(raw_input())

Solution (Python):
abs2 = lambda a,b: -(abs(int(1.0*a/b)))

def number(begin):
	global i
	
	if begin[i] == "(":
		i += 1
		res = expression(begin)
		i += 1 
		return res
	
	res = 0
	
	while begin[i].isdigit():
		res *= 10
		res += int(begin[i])
		i+=1
	
	return res
	
def term(begin):

	global i
	res = number(begin)
	
	while True:
		if begin[i] == "*":
			i += 1
			res *= number(begin)
		elif begin[i] == "/":
			i += 1
			num = number(begin)
			if res < 0 or num < 0:
				res = abs2(res,num)
			else:
				res /= num
		else:
			break
	return res
	
def expression(begin):
	
	global i
	res = term(begin)
	
	while True:
		if begin[i] == "+":
			i += 1
			res += term(begin)
			
		elif begin[i] == "-":
			i += 1
			res -= term(begin)
		else:
			break
	return res
	

def main():
	global i
	for j in range(input()):
			i = 0
			ex = raw_input() +"="
			ans = expression(ex)
	
			print ans
main()