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: Accepted

Solution code:
#!/usr/bin/python3

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))

Submission status: Accepted

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:
            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)

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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])))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

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))

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

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

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

Submission status: Accepted

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

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)))

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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])))

Submission status: Accepted

Solution code:
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])))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

# 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

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])

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
# AOJ 0109 Smart Calculator
# Python3 2018.6.18 bal4u

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])

Submission status: Accepted

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 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))

Submission status: Accepted

Solution code:
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())

Submission status: Accepted

Solution code:
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):# your code goes here

	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()

Submission status: Accepted

Solution code:
def divide(x, y):
    s = 1
    if(x < 0):s *= -1
    if(y < 0):s *= -1
    return abs(x) / abs(y) * s     

operator = {"+":(lambda x,y: x+y),
            "-":(lambda x,y: x-y),
            "*":(lambda x,y: x*y),
            "/":divide
            }

def ind(src, x):
    if x not in src:return 1<<30
    return src.index(x)
 
def _split(_src):
    c = 0
    l = len(_src)
    if l == 0:
        return []
    while c < l and ord('0') <= ord(_src[c]) <= ord('9'):
        c += 1

    if c == 0:
        return [_src[0]] + _split(_src[1:])
    else:
        return [int(_src[:c])] + _split(_src[c:])
         
 
def evaluate(src):
    if len(src) == 1:
        return src[0]
         
    if "(" in src:
        l = src.index("(")
        r = l
        st = 1
        while st:
            r += 1
            if src[r] == "(": st += 1
            if src[r] == ")": st -= 1
        
        mid = evaluate(src[l + 1:r])
        return evaluate( src[:l] + [mid] + src[r + 1:])
    
    if "*" in src or "/" in src:
        pos = min(ind(src, "*"), ind(src,"/"))
        op = src[pos]
        l, r = src[pos - 1], src[pos + 1]
        mid = operator[op](l, r)
        return evaluate(src[:pos - 1] + [mid] + src[pos + 2:])
    
    else:
        pos = min(ind(src, "+"), ind(src, "-"))
        op = src[pos]
        l, r = src[pos - 1], src[pos + 1]
        mid = operator[op](l, r)
        return evaluate(src[:pos - 1] + [mid] + src[pos + 2:])
     
for t in xrange(input()):
    _src = raw_input().strip("=")
    src = _split(_src)
    print evaluate(src)

Submission status: Accepted

Solution code:
def divide(x, y):
    s = 1
    if(x < 0):s *= -1
    if(y < 0):s *= -1
    return abs(x) / abs(y) * s     

operator = {"+":(lambda x,y: x+y),
            "-":(lambda x,y: x-y),
            "*":(lambda x,y: x*y),
            "/":divide
            }

def ind(src, x):
    if x not in src:return 1<<30
    return src.index(x)
 
def _split(_src):
    c = 0
    l = len(_src)
    if l == 0:
        return []
    while c < l and ord('0') <= ord(_src[c]) <= ord('9'):
        c += 1

    if c == 0:
        return [_src[0]] + _split(_src[1:])
    else:
        return [int(_src[:c])] + _split(_src[c:])
         
 
def evaluate(src):
    if len(src) == 1:
        return src[0]
         
    if "(" in src:
        l = src.index("(")
        r = l
        st = 1
        while st:
            r += 1
            if src[r] == "(": st += 1
            if src[r] == ")": st -= 1
        
        mid = evaluate(src[l + 1:r])
        return evaluate( src[:l] + [mid] + src[r + 1:])
    
    pos = min(ind(src, "*"), ind(src,"/"))
    if(pos == 1<<30):
        pos = min(ind(src, "+"), ind(src, "-"))
    op = src[pos]
    l, r = src[pos - 1], src[pos + 1]
    mid = operator[op](l, r)
    return evaluate(src[:pos - 1] + [mid] + src[pos + 2:])

     
for t in xrange(input()):
    _src = raw_input().strip("=")
    src = _split(_src)
    print evaluate(src)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin, exit
from operator import add, sub, mul, truediv


def div(a, b):
    return int(truediv(a, b))


class Parser(list):
    """
    <statement> ::= <expression> "="
    <expression> ::= <term> [ ("+"|"-") <term> ]
    <term> ::= <factor> [ ("*"|"/") <factor> ]
    <factor> ::= <number> | "(" <expression> ")"
    """

    def __init__(self, tokens):
        self._iter_tokens = iter(tokens)

        self._next_symbol()
        while self.symbol != '=':
            self._expression()

    def _expression(self, fn_table={'+': add, '-': sub}):
        if self.symbol in fn_table:
            op_sign = self.symbol
            self._next_symbol()
            self._term()
            self.append(fn_table[op_sign])
        else:
            self._term()

        while self.symbol in fn_table:
            op_sign = self.symbol
            self._next_symbol()
            self._term()
            self.append(fn_table[op_sign])

    def _term(self, fn_table={'*': mul, '/': div}):
        self._factor()
        while self.symbol in fn_table:
            op_sign = self.symbol
            self._next_symbol()
            self._factor()
            self.append(fn_table[op_sign])

    def _factor(self):
        if self.symbol.isdigit():
            self.append(int(self.symbol))
            self._next_symbol()
        elif self.symbol == '(':
            self._next_symbol()
            self._expression()
            if self.symbol != ')':
                raise SyntaxError(self.symbol)
            self._next_symbol()
        else:
            raise SyntaxError(self.symbol)

    def _next_symbol(self):
        self.symbol = next(self._iter_tokens)


def tokenize(line):
    buf = []
    tokens = []

    for c in line:
        if c.isdigit():
            buf.append(c)
        else:
            if buf:
                tokens.append(''.join(buf))
                del buf[:]
            tokens.append(c)
            if c == '=':
                return tokens


def run(commands):
    stack = []

    for cmd in commands:
        if isinstance(cmd, int):
            stack.append(cmd)
        else:
            buf = stack.pop()
            stack[-1] = cmd(stack[-1], buf)
    return stack[-1]


def main(readline=stdin.readline):
    for _ in range(int(readline())):
        print(run(Parser(tokenize(readline()))))
    exit()


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s = ""; l = 0;
def expr(idx):
    ret, idx = term(idx)
    while idx<l:
        if s[idx]=='+':
            r, idx = term(idx+1)
            ret += r
        elif s[idx]=='-':
            r, idx = term(idx+1)
            ret -= r
        else:
            break
    return ret, idx
    
def term(idx):
    ret, idx = fact(idx)
    while idx<l:
        if s[idx]=='*':
            r, idx = fact(idx+1)
            ret *= r
        elif s[idx]=='/':
            r, idx = fact(idx+1)
            ret = abs(ret) / abs(r) * (-1 if ret*r<0 else 1)
        else:
            break
    return ret, idx

def fact(idx):
    ret = 0
    if s[idx]=='(':
        ret, idx = expr(idx+1)
        idx += 1
    else:
        ret, idx = num(idx)
    return ret, idx

def num(idx):
    ret = 0
    while idx<l and s[idx].isdigit():
        ret = 10*ret + int(s[idx])
        idx+=1
    return ret, idx

for i in xrange(input()):
    s = raw_input(); l = len(s);
    print expr(0)[0]