Problem:
Smart Calculator Your task is to write a program which reads an expression and evaluates it.  The expression consists of numerical values, operators and parentheses, and the ends with '='.  The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division.  Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right.  You may assume that there is no division by zero.  All calculation is performed as integers, and after the decimal point should be truncated  Length of the expression will not exceed 100.  -1 × 10 9 ≤ intermediate results of computation ≤ 10 9  Input The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression. Output For each datasets, prints the result of calculation. Sample Input 2
4-2*3=
4*(8+4+3)= Output for the Sample Input -2
60

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

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

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

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

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

Solution (Python):

'''
所要時間は、分位であった。
'''




import sys
input = sys.stdin.readline


from collections import deque


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

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

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

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

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

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

Solution (Python):
import re
class Num:
    def __str__(self):
        return str(self.x)
    def __init__(self, value):
        self.x = value
    def __add__(self, value):
        return Num(self.x + value.x)
    def __sub__(self, value):
        return Num(self.x - value.x)
    def __mul__(self, value):
        return Num(self.x * value.x)
    def __truediv__(self, value):
        return Num(int(self.x / value.x))

N = int(input())
for i in range(N):
    s = input()[:-1]
    s = re.sub(r'(\d+)',r'Num(\1)',s)
    print(eval(s))

Solution (Python):

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

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

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

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

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