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:
import math
def calc_zyouzyo(siki) :
    j = 0
    while True :
        if '*' not in siki and '/' not in siki:
            break
        if siki[j] == '*' :
            siki[j-1] = str(int(siki[j-1]) * int(siki[j+1]))
            del siki[j:j+2]
        elif siki[j] == '/' :
            if (int(siki[j-1]) < 0 and int(siki[j+1]) < 0) or (int(siki[j-1]) >= 0 and int(siki[j+1]) >= 0) :
                siki[j-1] = str(int(siki[j-1]) // int(siki[j+1]))
            else :
                if int(siki[j-1]) % int(siki[j+1]) == 0 :
                    siki[j-1] = str(int(siki[j-1]) // int(siki[j+1]))
                else :
                    siki[j-1] = str(int(siki[j-1]) // int(siki[j+1]) + 1)
            del siki[j:j+2]
        else :
            j += 1
    if len(siki) == 1 :
        return(siki[0])
    else :
        return(siki)
    
def calc_kagen(siki) :
    j = 0
    while True :
        if '+' not in siki and '-' not in siki:
            break
        if siki[j] == '+' :
            siki[j-1] = str(int(siki[j-1]) + int(siki[j+1]))
            del siki[j:j+2]
        elif siki[j] == '-' :
            siki[j-1] = str(int(siki[j-1]) - int(siki[j+1]))
            del siki[j:j+2]
        else :
            j += 1
    if len(siki) == 1 :
        return(siki[0])
    else :
        return(siki)

def calc(siki) :
    siki = calc_zyouzyo(siki)
    siki = calc_kagen(siki)
    return(siki)

n = int(input())
for i in range(n) :
    tmp = list(input())
    siki = []
    num = ''
    for j in range(len(tmp)) :
        if tmp[j] in ['*', '/', '+', '-', '(', ')', '='] :
            if num != '' :
                siki.append(num)
            siki.append(tmp[j])
            num = ''
        else :
            num += tmp[j]
    siki.remove('=')
    j = 0
    while True :
        if j == len(siki) or ')' not in siki:
            break
        stack = []
        if siki[j] == ')' :
            for k in range(j-1,-1, -1) :
                if siki[k] == '(' :
                    break
                else :
                    stack.append(siki[k])
            stack.reverse()
            siki[k] = calc(stack)
            del siki[k+1 : j+1]
            j = k+1
        else :
            j += 1
    siki = calc(siki)
    print(siki)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
'''
所要時間は、分位であった。
'''


# ライブラリのインポート
#import re
import sys
input = sys.stdin.readline
#import heapq
#import bisect
from collections import deque
#import math

def main():
    n = int(input())
    for _ in range(n): 
        IN = input().strip()
        exp1 = calcmold(IN)
        exp2 = calc1(exp1)
        exp3 = calcmult(exp2)
        print(calcplus(exp3))

def calcmold(exp):
    # seikei
    tmp = ""
    EXP = deque()
    oplist = ["+","-","*","/","(",")","="]
    for i in range(len(exp)):
        if exp[i] not in oplist:
            tmp += exp[i]
        else:
            if tmp == "":
                EXP.append(exp[i])
                continue
            EXP.append(int(tmp))
            EXP.append(exp[i])
            tmp = ""
    return EXP


def calc1(IN):
    #calculate()
    EXP = deque()
    while(IN):
        check = IN.popleft()
        if check == ")":
            TMP = deque()
            while(1):
                look = EXP.pop()
                if look == "(": break
                TMP.appendleft(look)
            TMP.append("=")
            EXP.append(calcplus(calcmult(TMP)))
        else: EXP.append(check)
    return EXP
        


def calcmult(exp):
    # no()
    EXP = deque()
    while(exp):
        check = exp.popleft()
        if check == "*":
            arg1 = EXP.pop()
            arg2 = exp.popleft()
            EXP.append(arg1*arg2)
        elif check == "/":
            arg1 = EXP.pop()
            arg2 = exp.popleft()
            EXP.append(int(arg1/arg2))
        else: EXP.append(check)
    return EXP


def calcplus(exp):
    # no()
    EXP = deque()
    while(exp):
        check = exp.popleft()
        if check == "+":
            arg1 = EXP.pop()
            arg2 = exp.popleft()
            EXP.append(arg1+arg2)
        elif check == "-":
            arg1 = EXP.pop()
            arg2 = exp.popleft()
            EXP.append(arg1-arg2)
        elif check == "=":
            return EXP.pop()
        else: EXP.append(check)
    return EXP
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import heapq
from collections import deque
from enum import Enum
import sys
import math
from _heapq import heappush, heappop
import copy

BIG_NUM = 2000000000
MOD = 1000000007
EPS = 0.000000001



line = []

def calc_E(left,right):
    global line

    depth = 0
    Q = deque()

    #深さ0の、プラスまたはマイナスを探す(単項の-は無いものとする)
    i = left
    while i <= right:
        if line[i] == '(':
            depth += 1
        elif line[i] == ')':
            depth -= 1

        if depth != 0:
            i += 1
        elif line[i] != '+' and line[i] != '-':
            i += 1
        else:
            Q.append(i)
            i += 1

    if len(Q) == 0:
        return calc_T(left,right)

    tmp = calc_E(left,Q[0]-1)

    while len(Q) > 0:
        loc = Q.popleft()

        tmp_right = None

        if len(Q) == 0:
            tmp_right = calc_T(loc+1,right)
        else:
            tmp_right = calc_T(loc+1,Q[0]-1)

        if line[loc] == '+':
            tmp += tmp_right
        else:
            tmp -= tmp_right

    return tmp


def calc_T(left,right):
    global line

    depth = 0
    Q = deque()

    #深さ0の、*または/を探す
    i = left
    while i <= right:
        if line[i] == '(':
            depth += 1
        elif line[i] == ')':
            depth -= 1

        if depth != 0:
            i += 1
        elif line[i] != '*' and line[i] != '/':
            i += 1
        else:
            Q.append(i)
            i += 1

    if len(Q) == 0:
        return calc_F(left,right)

    tmp = calc_T(left,Q[0]-1)

    while len(Q) > 0:
        loc = Q.popleft()

        tmp_right = None

        if len(Q) == 0:
            tmp_right = calc_F(loc+1,right)
        else:
            tmp_right = calc_F(loc+1,Q[0]-1)

        if line[loc] == '*':
            tmp *= tmp_right
        else: #注意:たとえば(-3//2はpython3では-2になる模様)
            if tmp*tmp_right > 0:
                tmp = abs(tmp)//abs(tmp_right)
            else:
                tmp = abs(tmp)//abs(tmp_right)
                tmp *= -1

    return tmp


def calc_F(left,right):
    if line[left].isdecimal():
        return calc_NUM(left,right)
    elif line[left] == '(':

        depth = 0
        close_pos = None

        for i in range(left,right+1):
            if line[i] == '(':
                depth += 1
            elif line[i] == ')':
                depth -= 1
                if depth == 0:
                    close_pos = i
                    break

        return calc_E(left+1,close_pos-1)

def calc_NUM(left,right):
    global line
    ret = 0

    for i in range(left,right+1):
        ret = 10*ret+int(line[i])

    return ret

N = int(input())

for _ in range(N):
    line = str(input())
    print("%d"%(calc_E(0,len(line)-2)))

Submission status: Accepted

Solution code:
class c:
    def __init__(self, v):
        self.value = v
    def __str__(self):
        return str(self.value)
    def __add__(self, other):
        return c(self.value + other.value)
    def __sub__(self, other):
        return c(self.value - other.value)
    def __mul__(self, other):
        return c(self.value * other.value)
    def __truediv__(self, other):
        return c(int(self.value / other.value))

import re

n = int(input())

ans = (str(eval(re.sub(r'(\d+)', r'c(\1)', input()[:-1]))) for i in range(n))

print('\n'.join(ans))

Submission status: Accepted

Solution code:
from inspect import currentframe
from sys import exit, stderr

tokens = []
cur = 0
def debug(*args):
    names = {id(v):k for k,v in currentframe().f_back.f_locals.items()}
    print(', '.join(names.get(id(arg),'???') + str(id(arg)) +' = '+repr(arg) for arg in args), file=stderr)
def parse_expr():
    global cur
    if tokens[cur] == "=":
        return
    lhs = parse_mul()
    while(tokens[cur] == "+" or tokens[cur] == "-"):
        if tokens[cur] == "+":
            cur += 1
            lhs += parse_mul()
        elif tokens[cur] == "-":
            cur += 1
            lhs -= parse_mul()
        # debug(lhs, cur)
    return lhs

def parse_mul():
    global cur
    lhs = parse_term()
    while(tokens[cur] == "*" or tokens[cur] == "/"):
        if tokens[cur] == "*":
            cur += 1
            lhs *= parse_term()
        elif tokens[cur] == "/":
            cur += 1
            divisor = parse_term()
            if lhs < 0 and lhs % divisor != 0:
                lhs //= divisor
                lhs += 1
            else:
                lhs //= divisor
    return lhs

def parse_term():
    global cur
    if tokens[cur].isdigit():
        lhs = int(tokens[cur])
        cur += 1
        while(tokens[cur].isdigit()):
            lhs *= 10
            lhs += int(tokens[cur])
            cur += 1
    elif tokens[cur] == "(":
        cur += 1
        lhs = parse_expr()
        if tokens[cur] != ")":
            raise Exception("not closed")
        cur += 1
    return lhs

N = int(input())
for _ in range(N):
    src = list(str(input()))
    tokens = [tok for tok in src if tok != " "]
    cur = 0

    print(parse_expr())

Submission status: Accepted

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

def solve(s):

    def expr(l):
        left, mid = term(l)
        return edum(mid, left)
    
    def edum(l, lval):
        if s[l] == '+':
            val, mid = term(l + 1)
            return edum(mid, lval + val)
        if s[l] == '-':
            val, mid = term(l + 1)
            return edum(mid, lval - val)
        else:
            return lval, l
    
    def term(l):
        left, mid = value(l)
        return tdum(mid, left)

    def tdum(l, lval):
        if s[l] == '*':
            l += 1
            val1, mid = value(l)
            return tdum(mid, lval * val1)
        if s[l] == '/':
            l += 1
            val1, mid = value(l)
            return tdum(mid, (abs(lval) // abs(val1)) * (-1 if (lval < 0) ^ (val1 < 0) else 1))
        else:
            return lval, l

    def value(l):
        if s[l] == '(':
            val1, mid = expr(l + 1)
            return val1, mid + 1
        else:
            val = 0
            fl =  s[l] == '-'
            if fl:
                l += 1
            while s[l].isdecimal():
                val *= 10
                val += int(s[l])
                l += 1
            if fl:
                val *= -1
            return val, l

    res = expr(0)[0]
    """
    gnd = eval(''.join(s[:-1]).replace('/', '//'))
    while res != gnd:
        pass
    """
    print(res)

def main():
    q = int(input())
    for _ in range(q):
        solve(list(input()))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import re
import decimal

def main():
    decimal.getcontext().rounding = decimal.ROUND_DOWN
    n = int(input())
    for i in range(n):
        s = input()
        s = re.sub(r'(\d+)', r'decimal.Decimal(\1)', s).replace('=', '').replace('/', '//')
        print(int(eval(s)))

main()

Submission status: Accepted

Solution code:
from collections import deque

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

n = int(input())
for i in range(n):
    s = input()
    out = []
    ope = deque([])
    for j in range(len(s)):
        inp = s[j]
        if inp == "=":
            while len(ope):
                out.append(ope.pop())
            break
        elif inp.isdecimal():
            if len(out) and s[j - 1].isdecimal():
                tmp = out.pop()
                out.append(tmp*10 + int(inp))
            else:
                out.append(int(inp))
        elif inp == "(":
            ope.append(inp)
        elif inp == ")":
            while True:
                tmp = ope.pop()
                if tmp == "(":
                    break
                out.append(tmp)
        elif priority[inp] == 1:
            while len(ope) and priority[ope[-1]] >= 1:
                tmp = ope.pop()
                out.append(tmp)
            else:
                ope.append(inp)
        elif priority[inp] == 0:
            while len(ope) and priority[ope[-1]] >= 0:
                tmp = ope.pop()
                out.append(tmp)
            else:
                ope.append(inp)
    ans = deque([])
    for k in range(len(out)):
        if out[k] == "+":
            a = ans.pop()
            ans[-1] += a
        elif out[k] == "-":
            a = ans.pop()
            ans[-1] -= a
        elif out[k] == "*":
            a = ans.pop()
            ans[-1] *= a
        elif out[k] == "/":
            a = ans.pop()
            b = ans.pop()
            ans.append(int(b/a))
        else:
            ans.append(out[k])
    print(ans[0])

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]
    d=re.sub(r'(\d+)',r'c(\1)',s)
    #print(d)
    print(eval(d))
    #s.group(1)

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)))
n = int(input())
for i in range(n):
    print(eval(re.sub(r'(\d+)',r'c(\1)',input()[:-1])))

Submission status: Runtime Error

Solution code:
from collections import deque

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


def calc(exp,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
        else:
            temp = "" # 数値 2桁以上にも対応させる
            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):
    exp = input()
    print(calc(exp))

Submission status: Runtime Error

Solution code:
from collections import deque

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


def calc(exp,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
        else:
            temp = "" # 数値 2桁以上にも対応させる
            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):
    exp = input()
    print(calc(exp))

Submission status: Runtime Error

Solution code:
from collections import deque

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


def calc(exp,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
        else:
            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: Runtime Error

Solution code:
for _ in range( int(raw_input()) ): print int(eval( "1.0"+raw_input()[:-1] ))

Submission status: Runtime Error

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=x.pop()/a
      x.append(a)
      f==""

  s=x[:]
  x=[]
  f=""
  for e in s:
    if e=="+" or e=="-": f=e
    else:
      a=int(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: Runtime Error

Solution code:
N = int(raw_input())
for loop in xrange(N):
    print eval(raw_input().replace("/","//"))

Submission status: Runtime Error

Solution code:
ops = {"+": lambda a, b: b + a,
       "-": lambda a, b: b - a,
       "*": lambda a, b: b * a,
       "/": lambda a, b: b // a}

def calc(temp, v):
    if v in ops:
        temp.append(ops[v](temp.pop(), temp.pop()))
    else:
        temp.append(int(v))
    return temp

n = input()
for i in range(n):
    porand = []
    temp = []
    formula = raw_input()
    for j in formula:
        if j >= "0" and j <= "9": porand.append(j)
        elif (j == "*" or j == "/") or j == "(": temp.append(j)
        elif j == "+" or j == "-":
            if len(temp) > 0:
                for k in reversed(temp):
                    if k == "*" or k == "/": porand.append(temp.pop())
                    else: break
            temp.append(j)
        elif j == ")":
            for k in reversed(temp):
                if k == "(":
                    temp.pop()
                    break
                porand.append(temp.pop())
        elif j == "=":
            for k in reversed(temp): porand.append(k)
    print reduce(calc, porand, [])[-1]

Submission status: Runtime Error

Solution code:
ops = {"+": lambda a, b: b + a,
       "-": lambda a, b: b - a,
       "*": lambda a, b: b * a,
       "/": lambda a, b: b / a}

def calc(temp, v):
    if v in ops:
        temp.append(ops[v](temp.pop(), temp.pop()))
    else:
        temp.append(int(v))
    return temp

n = input()
for i in range(n):
    porand = []
    temp = []
    formula = raw_input()
    for j in formula:
        if j >= "0" and j <= "9": porand.append(j)
        elif (j == "*" or j == "/") or j == "(": temp.append(j)
        elif j == "+" or j == "-":
            if len(temp) > 0:
                for k in reversed(temp):
                    if k == "*" or k == "/": porand.append(temp.pop())
                    else: break
            temp.append(j)
        elif j == ")":
            for k in reversed(temp):
                if k == "(":
                    temp.pop()
                    break
                porand.append(temp.pop())
        elif j == "=":
            for k in reversed(temp): porand.append(k)
    print reduce(calc, porand, [])[-1]

Submission status: Runtime Error

Solution code:
ops = {"+": lambda a, b: b + a,
       "-": lambda a, b: b - a,
       "*": lambda a, b: b * a,
       "/": lambda a, b: b / a,
       "@": lambda a, b: -(abs(int(1.0*a/b)))}

def calc(temp, v):
    if v in ["+", "-", "*"]:
        temp.append(ops[v](temp.pop(), temp.pop()))
    elif v == "/":
        if temp[-1] < 0 or temp[-2] < 0: temp.append(ops["@"](temp.pop(), temp.pop()))
        else: temp.append(ops[v](temp.pop(), temp.pop()))
    else:
        temp.append(int(v))
    return temp

n = input()
for i in range(n):
    porand = []
    temp = []
    formula = raw_input()
    for j in formula:
        if j >= "0" and j <= "9": porand.append(j)
        elif (j == "*" or j == "/") or j == "(": temp.append(j)
        elif j == "+" or j == "-":
            if len(temp) > 0:
                for k in reversed(temp):
                    if k == "*" or k == "/": porand.append(temp.pop())
                    else: break
            temp.append(j)
        elif j == ")":
            for k in reversed(temp):
                if k == "(":
                    temp.pop()
                    break
                porand.append(temp.pop())
        elif j == "=":
            for k in reversed(temp): porand.append(k)
    print reduce(calc, porand, [])[-1]

Submission status: Runtime Error

Solution code:
ops = {"+": lambda a, b: b + a,
       "-": lambda a, b: b - a,
       "*": lambda a, b: b * a,
       "/": lambda a, b: b / a,
       "@": lambda a, b: -(abs(int(1.0*b/a)))}

def calc(stack, v):
    if v in ["+", "-", "*"]:
        stack.append(ops[v](stack.pop(), stack.pop()))
    elif v == "/":
        if stack[-1] < 0 or stack[-2] < 0: stack.append(ops["@"](stack.pop(), stack.pop()))
        else: stack.append(ops[v](stack.pop(), stack.pop()))
    else:
        stack.append(int(v))
    return stack

n = input()
for i in range(n):
    porand = []
    temp = []
    stack = []
    formula = raw_input()
    for j in formula:
        if j >= "0" and j <= "9": porand.append(j)
        elif (j == "*" or j == "/") or j == "(": stack.append(j)
        elif j == "+" or j == "-":
            if len(stack) > 0:
                for k in reversed(stack):
                    if k == "*" or k == "/": temp.append(stack.pop())
                    else:
                        porand.extend(temp)
                        temp = []
                        break
            temp.append(j)
        elif j == ")":
            for k in reversed(stack):
                if k == "(":
                    porand.extend(temp)
                    stack.pop()
                    break
                else: temp.append(stack.pop())
        elif j == "=": porand.extend(stack)
    print reduce(calc, porand, [])[-1]

Submission status: Runtime Error

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

Submission status: Runtime Error

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