calculator

mail@pastecode.io avatar
unknown
python
2 years ago
2.2 kB
19
Indexable
Never
def Level(char):
    if(char=='*' or char=='/'):
        return 3
    elif(char=='+' or char=='-'):
        return 2
    else:
        return 1
def post(charlist):
    po=[]
    stack=[]
    for char in charlist:
        this_level=Level(char)
        if(char=='('):
            stack.append(char)
        elif(char==')'):
            while(len(stack)!=0 and stack[-1]!='('):
                x=stack.pop()
                po.append(x)
            if(len(stack)!=0 and stack[-1]=='('):
                stack.pop()
        elif(this_level>1):
            if(len(stack)!=0):
                check_level=Level(stack[-1])
                while(len(stack)!=0 and this_level<=check_level):
                    #print(stack[-1])
                    po.append(stack.pop())
                    if(len(stack)!=0):
                        check_level=Level(stack[-1])
            stack.append(char)
            #print(stack)
        else:
            po.append(char)
    while(len(stack)!=0):
        po.append(stack.pop())
    return po
def calculate(polist):
    stack=[]
    for x in polist:
        if(x=='+'):
            n1=stack.pop()
            n2=stack.pop()
            stack.append(n2+n1)
        elif(x=='-'):
            n1=stack.pop()
            n2=stack.pop()
            stack.append(n2-n1)
        elif(x=='*'):
            n1=stack.pop()
            n2=stack.pop()
            stack.append(n2*n1)
        elif(x=='/'):
            n1=stack.pop()
            n2=stack.pop()
            if(n2//n1<0 and n2%n1!=0):
                stack.append(n2//n1+1)
            else:
                stack.append(n2//n1)
        else:
            stack.append(x)
    return stack[0]
if __name__=="__main__":
    tmp=input()
    charlist=[]
    for i in range(len(tmp)):
        charlist.append(tmp[i])
    polist=post(charlist)    
    T=int(input())
    for _ in range(T):
        numberlist=list(map(int,input().split()))
        j=0
        for i in range(len(polist)):
            if(Level(polist[i])==1):
                polist[i]=numberlist[j]
                j+=1
        print(calculate(polist))