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: Wrong Answer

Solution code:
import re

def factor(t, i):
    if t[i[0]] == '(':
        i[0] += 1
        r = expr(t, i)
        i[0] += 1
        return r
    else:
        i[0] += 1
        return int(t[i[0]-1])

def term(t, i):
    r = factor(t, i)
    while True:
        if t[i[0]] == '*':
            i[0] += 1
            r *= factor(t, i)
        elif t[i[0]] == '/':
            i[0] += 1
            r /= factor(t, i)
        else:
            break
    return r

def expr(t, i):
    r = term(t, i)
    while True:
        if t[i[0]] == '+':
            i[0] += 1
            r += term(t, i)
        elif t[i[0]] == '-':
            i[0] += 1
            r -= term(t, i)
        else:
            break
    return r

n = int(raw_input())
for _ in range(n):
    t = re.sub(r'([\+\-\*\/\(\)=])', r' \1 ', raw_input()).split()
    print expr(t, [0])

Submission status: Wrong Answer

Solution code:
import re

def factor(t, i):
    if t[i[0]] == '(':
        i[0] += 1
        r = expr(t, i)
        i[0] += 1
        return r
    else:
        i[0] += 1
        return int(t[i[0]-1])

def term(t, i):
    r = factor(t, i)
    while True:
        if t[i[0]] == '*':
            i[0] += 1
            r *= factor(t, i)
        elif t[i[0]] == '/':
            i[0] += 1
            r /= factor(t, i)
        else:
            break
    return r

def expr(t, i):
    r = term(t, i)
    while True:
        if t[i[0]] == '+':
            i[0] += 1
            r += term(t, i)
        elif t[i[0]] == '-':
            i[0] += 1
            r -= term(t, i)
        else:
            break
    return r

n = int(raw_input())
for _ in range(n):
    t = [s for s in re.sub(r'([\+\-\*\/\(\)=])', r' \1 ', raw_input()).split() if s != '']
    print expr(t, [0])

Submission status: Wrong Answer

Solution code:
for t in xrange(input()):
	print eval(raw_input()[:-1])

Submission status: Wrong Answer

Solution code:
def divide(x, y):
    s = 1
    if(x < 0):s *= -1
    if(y < 0):s *= -1
    if x == 0:exit()
    return abs(x) / abs(y) * s     
 
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:])
     
    operators = [("+", lambda x,y:x + y),
                 ("-", lambda x,y:x - y),
                 ("*", lambda x,y:x * y),
                 ("/", divide)
                ]  
     
    for (op,func) in operators:
        if op in src:
            p = src.index(op)
            l = evaluate(src[:p])
            r = evaluate(src[p + 1:])
            return func(l, r)
     
for t in xrange(input()):
    _src = raw_input().strip("=")
    src = _split(_src)
    print evaluate(src)

Submission status: Wrong Answer

Solution code:
def divide(x, y):
    s = 1
    if(x < 0):s *= -1
    if(y < 0):s *= -1
    return abs(x) / abs(y) * s     
 
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:])
     
    operators = [("+", lambda x,y:x + y),
                 ("-", lambda x,y:x - y),
                 ("*", lambda x,y:x * y),
                 ("/", divide)
                ]  
     
    for (op,func) in operators:
        if op in src:
            p = src.index(op)
            l = evaluate(src[:p])
            r = evaluate(src[p + 1:])
            return func(l, r)
     
for t in xrange(input()):
    _src = raw_input().strip("=")
    src = _split(_src)
    print evaluate(src)

Submission status: Wrong Answer

Solution code:
def divide(x, y):
    s = 1
    if(x < 0):s *= -1
    if(y < 0):s *= -1
    return abs(x) / abs(y) * s     
 
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:])
     
    operators = [("+", lambda x,y:x + y),
                 ("-", lambda x,y:x - y),
                 ("*", lambda x,y:x * y),
                 ("/", divide)
                ]  
     
    for (op,func) in operators:
        if op in src:
            p = len(src) - 1 - src[::-1].index(op)
            l = evaluate(src[:p])
            r = evaluate(src[p + 1:])
            return func(l, r)
     
for t in xrange(input()):
    _src = raw_input().strip("=")
    src = _split(_src)
    print evaluate(src)

Submission status: Wrong Answer

Solution code:
def divide(x, y):
    s = 1
    if(x < 0):s *= -1
    if(y < 0):s *= -1
    return abs(x) / abs(y) * s     
 
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:])
     
    operators = [("+", lambda x,y:x + y),
                 ("-", lambda x,y:x - y),
                 ("/", divide),
                 ("*", lambda x,y:x * y)
                ]  
     
    for (op,func) in operators:
        if op in src:
            p = len(src) - 1 - src[::-1].index(op)
            l = evaluate(src[:p])
            r = evaluate(src[p + 1:])
            return func(l, r)
     
for t in xrange(input()):
    _src = raw_input().strip("=")
    src = _split(_src)
    print evaluate(src)

Submission status: Wrong Answer

Solution code:
import sys

for s in sys.stdin:
	if '=' in s:
		print eval(s.strip().strip('='))

Submission status: Wrong Answer

Solution code:
import sys

for s in sys.stdin:
	if '=' in s:
		print int(eval(s.strip().strip('=')))

Submission status: Wrong Answer

Solution code:
for i in xrange(input()):
	print int(eval(raw_input().strip().strip('=')))

Submission status: Wrong Answer

Solution code:
for i in xrange(input()):
	print int(eval(raw_input().strip().strip('=').replace('/','//')))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin, exit


def main(readline=stdin.readline):
    n = int(readline())
    for _ in range(n):
        print(eval(readline().replace('/', '//').replace('=', '')))
    exit()


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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


OPERATOR = {'+': add, '-': sub, '*': mul, '/': floordiv}


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):
        if self.symbol in ('+', '-'):
            op_sign = self.symbol
            self._next_symbol()
            self._term()
            self.append(OPERATOR[op_sign])
        else:
            self._term()

        while self.symbol in ('+', '-'):
            op_sign = self.symbol
            self._next_symbol()
            self._term()
            self.append(OPERATOR[op_sign])

    def _term(self):
        self._factor()
        while self.symbol in ('*', '/'):
            op_sign = self.symbol
            self._next_symbol()
            self._factor()
            self.append(OPERATOR[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: Wrong Answer

Solution code:
n = input()
for i in range(n):
    str = raw_input()[:-1]
    print eval(str)

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
for i in range(n):
    e = raw_input()
    print eval(e[:len(e)-1])

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
for i in range(n):
    e = map(str, raw_input().split("/"))
    a = "//".join(map(str, e))
    print eval(a[:len(a)-1])

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
for i in range(n):
    e = map(str, raw_input().split("/"))
    a = "//".join(map(str, e))
    print eval(a[:-1])

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
for i in range(n):
    a = raw_input()
    print eval(a[:-1])

Submission status: Wrong Answer

Solution code:
n = input()
for i in range(n):
    print eval(raw_input().replace("/","//")[:-1])

Submission status: Wrong Answer

Solution code:
T = int(input())
for tc in range(0,T) :
	print(eval(input().replace("=","")))

Submission status: Wrong Answer

Solution code:
T = int(input())
for tc in range(0,T) :
	print(int(eval(input().replace("=",""))))

Submission status: Wrong Answer

Solution code:
T = int(input())
for tc in range(0,T) :
	print eval(raw_input().strip("="))

Submission status: Wrong Answer

Solution code:
T = int(input())
for tc in range(0,T) :
	print(input().strip("="))

Submission status: Wrong Answer

Solution code:
T = int(input())
for tc in range(0,T) :
	print(int(eval(input().strip("="))))

Submission status: Wrong Answer

Solution code:
T = int(input())
for tc in range(0,T) :
	print int(eval(raw_input().strip("=")))

Submission status: Wrong Answer

Solution code:
T = int(input())
for tc in range(0,T) :
	print int(eval(raw_input().strip('=')))

Submission status: Wrong Answer

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 /= r
        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]

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
while n:
    s = raw_input()
    print eval(s[:-1])
    n -= 1

Submission status: Time Limit Exceeded

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,brac=None):
    i = 0 # ループカウンタ?
    num = deque() # 数字をためておく
    ops = deque() # +-をためておく
    ope = "" # */を保存
    
    if not brac:
        # 対応する括弧の位置を記録しておいて計算量を削減
        brac = [-1 for j in range(len(exp))]
        tmpbrac = []
        for j in range(len(exp) - 1, 0, -1):
            if exp[j] == ')':
                tmpbrac.append(j)
            elif exp[j] == '(':
                brac[j] = tmpbrac.pop()

    # かっこの中身と乗除算
    while i < len(exp):
        # かっこの中身は再帰的に計算
        if exp[i] == '(':
            num.append(calc(exp[i + 1:brac[i]],brac))
            i = brac[i]
            if ope:
                r = num.pop()
                l = num.pop()
                num.append(eva(l, r, ope))
                ope = ""
        elif exp[i] in ["*", "/"]:
            ope = exp[i]
        elif exp[i] in ["+", "-"]:
            ops.append(exp[i])
        elif exp[i] == "=":
            pass
        elif exp[i].isnumeric():
            temp = exp[i] # 数値 2桁以上にも対応させる
            i += 1
            while i < len(exp) and exp[i].isnumeric():
                temp += exp[i]
                i += 1
            i -= 1 # 最後の数字に戻る(最後にi+=1しているのでこれでいい)
            num.append(int(temp))
            if ope:
                r = num.pop()
                l = num.pop()
                num.append(eva(l, r, ope))
                ope = ""
        i += 1
    while len(ops) != 0:
        num.appendleft(eva(num.popleft(),num.popleft(),ops.popleft()))

    return num[0]


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

Submission status: Time Limit Exceeded

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,brac=None):
    i = 0 # ループカウンタ?
    num = deque() # 数字をためておく
    ops = deque() # +-をためておく
    ope = "" # */を保存
    
    if not brac:
        # 対応する括弧の相対位置を記録しておいて計算量を削減
        brac = [-1 for j in range(len(exp))]
        tmpbrac = []
        for j in range(len(exp) - 1, 0, -1):
            if exp[j] == ')':
                tmpbrac.append(j)
            elif exp[j] == '(':
                brac[j] = tmpbrac.pop() - j

    # かっこの中身と乗除算
    while i < len(exp):
        # かっこの中身は再帰的に計算
        if exp[i] == '(':
            num.append(calc(exp[i + 1:i + brac[i]],brac[i+1:i+brac[i]]))
            i += brac[i] - 1
            if ope:
                r = num.pop()
                l = num.pop()
                num.append(eva(l, r, ope))
                ope = ""
        elif exp[i] in ["*", "/"]:
            ope = exp[i]
        elif exp[i] in ["+", "-"]:
            ops.append(exp[i])
        elif exp[i] == "=":
            pass
        elif exp[i].isnumeric():
            temp = exp[i] # 数値 2桁以上にも対応させる
            i += 1
            while i < len(exp) and exp[i].isnumeric():
                temp += exp[i]
                i += 1
            i -= 1 # 最後の数字に戻る(最後にi+=1しているのでこれでいい)
            num.append(int(temp))
            if ope:
                r = num.pop()
                l = num.pop()
                num.append(eva(l, r, ope))
                ope = ""
        i += 1
    while len(ops) != 0:
        num.appendleft(eva(num.popleft(),num.popleft(),ops.popleft()))
    return num[0]


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

Submission status: Time Limit Exceeded

Solution code:
def calc(array):
	while not len(array) == 1:
		if '*' in array:
			x = array.index('*')
			array[x + 1] = str(int(array[x - 1]) * int(array[x + 1]))
			del array[x - 1:x + 1]
			continue
		if '/' in array:
			x = array.index('/')
			array[x + 1] = str(int(array[x - 1]) / int(array[x + 1]))
			del array[x - 1:x + 1]
			continue
		if '-' in array:
			x = array.index('-')
			array[x + 1] = str(int(array[x - 1]) - int(array[x + 1]))
			del array[x - 1:x + 1]
			continue
		if '+' in array:
			x = array.index('+')
			array[x + 1] = str(int(array[x - 1]) + int(array[x + 1]))
			del array[x - 1:x + 1]
			continue
	return str(array[0])

n = input()
for i in xrange(n):
	array = list(raw_input())
	
	while '(' in array:
		x1 = array.index('(') + 1
		x2 = array.index(')')
		jon = array[x1:x2]
		array[x2] = calc(jon)
		del array[x1 - 1:x2]
	print calc(array[0:len(array) - 1])

Submission status: Time Limit Exceeded

Solution code:
def calc(array):
	while len(array) > 1:
		if '/' in array:
			c = array.index('/')
			array[c + 1] = array[c - 1] / array[c + 1]
			del array[c - 1:c + 1]
			continue
		if '*' in array:
			c = array.index('*')
			array[c + 1] = array[c - 1] * array[c + 1]
			del array[c - 1:c + 1]
			continue
		if '-' in array:
			c = array.index('-')
			array[c + 1] = array[c - 1] - array[c + 1]
			del array[c - 1:c + 1]
			continue
		if '+' in array:
			c = array.index('+')
			array[c + 1] = array[c - 1] + array[c + 1]
			del array[c - 1:c + 1]
			continue
	return array[0]

n = input()
for i in range(n):
	conflict = []
	for var in list(raw_input()):
		try:
			conflict.append(int(var))
		except:
			conflict.append(var)
	if '(' in conflict:
		c1 = conflict.index('(')
		c2 = conflict.index(')')
		conflict[c2] = calc(conflict[c1 + 1:c2])
		del conflict[c1:c2]
	print calc(conflict[0:len(conflict) - 1])

Submission status: Time Limit Exceeded

Solution code:
def calc(array):
	while len(array) > 1:
		if '/' in array:
			c = array.index('/')
			array[c + 1] = array[c - 1] / array[c + 1]
			del array[c - 1:c + 1]
			continue
		if '*' in array:
			c = array.index('*')
			array[c + 1] = array[c - 1] * array[c + 1]
			del array[c - 1:c + 1]
			continue
		if '-' in array:
			c = array.index('-')
			array[c + 1] = array[c - 1] - array[c + 1]
			del array[c - 1:c + 1]
			continue
		if '+' in array:
			c = array.index('+')
			array[c + 1] = array[c - 1] + array[c + 1]
			del array[c - 1:c + 1]
			continue
	return array[0]

n = input()
for i in range(n):
	conflict = []
	for var in list(raw_input()):
		try:
			conflict.append(int(var))
		except:
			conflict.append(var)
	while '(' in conflict:
		c1 = conflict.index('(')
		c2 = conflict.index(')')
		conflict[c2] = calc(conflict[c1 + 1:c2])
		del conflict[c1:c2]
	print calc(conflict[0:len(conflict) - 1])

Submission status: Time Limit Exceeded

Solution code:
def calc(array):
	while len(array) > 1:
		if '/' in array:
			c = array.index('/')
			array[c + 1] = array[c - 1] / array[c + 1]
			del array[c - 1:c + 1]
		elif '*' in array:
			c = array.index('*')
			array[c + 1] = array[c - 1] * array[c + 1]
			del array[c - 1:c + 1]
		elif '-' in array:
			c = array.index('-')
			array[c + 1] = array[c - 1] - array[c + 1]
			del array[c - 1:c + 1]
		elif '+' in array:
			c = array.index('+')
			array[c + 1] = array[c - 1] + array[c + 1]
			del array[c - 1:c + 1]
	return array[0]

n = input()
for i in range(n):
	conflict = []
	for var in list(raw_input()):
		try:
			conflict.append(int(var))
		except:
			conflict.append(var)
	while '(' in conflict:
		c1 = conflict.index('(')
		c2 = conflict.index(')')
		conflict[c2] = calc(conflict[c1 + 1:c2])
		del conflict[c1:c2]
	print calc(conflict[0:len(conflict) - 1])

Submission status: Time Limit Exceeded

Solution code:
def calc(array):
	while '(' in array:
		c1 = array.index('(')
		c2 = array.index(')')
		array[c2] = calc(array[c1 + 1:c2])
		del array[c1:c2]
	while len(array) > 1:
		if '/' in array:
			c = array.index('/')
			array[c + 1] = array[c - 1] / array[c + 1]
			del array[c - 1:c + 1]
		elif '*' in array:
			c = array.index('*')
			array[c + 1] = array[c - 1] * array[c + 1]
			del array[c - 1:c + 1]
		elif '-' in array:
			c = array.index('-')
			array[c + 1] = array[c - 1] - array[c + 1]
			del array[c - 1:c + 1]
		elif '+' in array:
			c = array.index('+')
			array[c + 1] = array[c - 1] + array[c + 1]
			del array[c - 1:c + 1]
	return array[0]

n = input()
for i in range(n):
	conflict = []
	for var in list(raw_input()):
		try:
			conflict.append(int(var))
		except:
			conflict.append(var)
	print calc(conflict[0:len(conflict) - 1])

Submission status: Time Limit Exceeded

Solution code:
def calc(array):
	while '(' in array:
		c1 = array.index('(')
		c2 = array.index(')')
		array[c2] = calc(array[c1 + 1:c2])
		del array[c1:c2]
	while len(array) > 1:
		if '/' in array:
			c = array.index('/')
			array[c + 1] = int(array[c - 1] / array[c + 1])
			del array[c - 1:c + 1]
		elif '*' in array:
			c = array.index('*')
			array[c + 1] = array[c - 1] * array[c + 1]
			del array[c - 1:c + 1]
		elif '-' in array:
			c = array.index('-')
			array[c + 1] = array[c - 1] - array[c + 1]
			del array[c - 1:c + 1]
		elif '+' in array:
			c = array.index('+')
			array[c + 1] = array[c - 1] + array[c + 1]
			del array[c - 1:c + 1]
	return array[0]

n = input()
for i in range(n):
	conflict = []
	for var in list(raw_input()):
		try:
			conflict.append(int(var))
		except:
			conflict.append(var)
	print calc(conflict[0:len(conflict) - 1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from sys import stderr

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):
        try:
            if exp[i] == '(':
                end = 1
                s = 1
                while True:
                    if exp[i+end] == "(":
                        s += 1
                    elif exp[i+end] == ")":
                        s -= 1
                    if s == 0:
                        break
                    end += 1
                num.append(calc(exp[i+1:i+end]))
                i += end
                if ope:
                    l = num.pop()
                    r = num.pop()
                    num.append(eva(l, r, ope))
                    ope = ""
            if exp[i] in ["*", "/"]:
                ope = exp[i]
            elif exp[i] in ["+", "-"]:
                ops.append(exp[i])
            elif exp[i] == "=":
                pass
            else:
                temp = ""
                j = 0
                while i + j < len(exp) and exp[i+j].isnumeric():
                    temp += exp[i+j]
                    j += 1
                num.append(int(temp))
                i += j - 1
                if ope:
                    num.append(eva(num.pop(), num.pop(), ope))
                    ope = ""
            i += 1
        except:
            stderr.write(exp)
    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))

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from sys import stderr

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):
    try:
        i = 0
        num = deque()
        ops = deque()
        ope = ""
        while i < len(exp):
            if exp[i] == '(':
                end = 1
                s = 1
                while True:
                    if exp[i+end] == "(":
                        s += 1
                    elif exp[i+end] == ")":
                        s -= 1
                    if s == 0:
                        break
                    end += 1
                num.append(calc(exp[i+1:i+end]))
                i += end
                if ope:
                    l = num.pop()
                    r = num.pop()
                    num.append(eva(l, r, ope))
                    ope = ""
            if exp[i] in ["*", "/"]:
                ope = exp[i]
            elif exp[i] in ["+", "-"]:
                ops.append(exp[i])
            elif exp[i] == "=":
                pass
            else:
                temp = ""
                j = 0
                while i + j < len(exp) and exp[i+j].isnumeric():
                    temp += exp[i+j]
                    j += 1
                num.append(int(temp))
                i += j - 1
                if ope:
                    num.append(eva(num.pop(), num.pop(), ope))
                    ope = ""
            i += 1
        while len(ops) != 0:
            l = num.popleft()
            r = num.popleft()
            num.appendleft(eva(l,r,ops.popleft()))
    except:
        stderr.write(exp)
    
    return num[0]


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

Submission status: Time Limit Exceeded

Solution code:
import sys

while True:
    line = raw_input()
    if line == '':
        break

    for i in range(int(line)):
        a = eval(raw_input().replace('/', '//')[:-1])
        sys.stderr.write(str(a))

Submission status: Time Limit Exceeded

Solution code:
import sys

while True:
    line = raw_input()
    if line == '':
        break

    sys.stderr.write(line)
    for i in range(int(line)):
        a = eval(raw_input().replace('/', '//')[:-1])
        print(str(a))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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