主要想法就是如果遇到括號,就一直遞迴下去
Python班完了再放到codepad上XDDD
http://sprout.tw/oj/chal/53947/
def get_pivot( s ): cnt = 0 for i in range( 3 , len( s ) ): if s[ i ] == '(': cnt += 1 elif s[ i ] == ')': cnt -= 1 elif cnt == 0 and s[ i ] == ' ': return i return -123456789; def f(s) : #print("in " + s); t = get_pivot(s); #print("t = "+str(t)); a=0; b=0; if (s[t-1] == ')') : tmpt=t-1; check=1; while (s[tmpt]!='(') or check!=0: tmpt-=1; if (s[tmpt]==')') : check+=1; elif (s[tmpt]=='(') : check-=1 a = f(s[tmpt:t]) else : tmpt=t-1; tmp=[]; while (s[tmpt]!=' ') : tmp.append(s[tmpt]); tmpt-=1; a=0; for i in range(len(tmp)-1,-1,-1) : a=a*10 + int(tmp[i]); if (s[t+1] == '(') : tmpt=t+1; check=1; while (s[tmpt]!=')') or check!=0: tmpt+=1; if (s[tmpt]==')') : check-=1; elif (s[tmpt]=='(') : check+=1; b = f(s[t+1:tmpt+1]) else : tmpt=t+1; tmp=[]; while (s[tmpt]!=')') : tmp.append(s[tmpt]); tmpt+=1; b=0; for i in range(0,len(tmp)) : b=b*10 + int(tmp[i]); #print(s + " : a=" + str(a) +" b= "+str(b)); if s[1]=='+' : return a+b; elif s[1]=='-' : return a-b; elif s[1]=='*' : return a*b; elif s[1]=='/' : return a//b; n=int(input()); for i in range(0,n) : s=input() tmp=get_pivot(s) if tmp==-123456789: print(s); else : if (s[0]!='(') : s = "(" + s + ")"; print(f(s));
沒有留言:
張貼留言